2017-11-11 4 views
0

각도 자습서 코드에서 hero-details.component를 사용하여 영웅 객체를 업데이트하고 생성하고 싶습니다.switchMap에서 promise 또는 실제 객체를 반환하십시오.

그래서 ID가없는 경로를 추가합니다.

경로

{ 
    path:'detail/:id', 
    component:HeroDetailComponent 
    }, 
    { 
    path:'detail', 
    component:HeroDetailComponent 
    } 

주인공 서비스

getHero(id: number): Promise<Hero> { 
    return this.getHeroes() 
    .then(heroes => heroes.find(hero => hero.id === id)); 
} 

그러나 나는 영웅 details.component 파일을 처리하는 방법을 모르겠어요. switchMap에서 URL에 ID가없는 경우 새 영웅을 반환하고 싶습니다. 하지만 이드가 있었다면 Promise<Hero> 객체를 반환하는 서비스를 호출했습니다. 이

ngOnInit():void{ 
    this.route.paramMap 
     .switchMap((params:ParamMap) => { 
      var id = +params['id']; 
      return id ? this.heroService.getHero(+params['id']) : new Hero(); 
     }) 
     .subscribe(hero => this.hero = hero); 
    } 

이 작업을 수행하는 가장 좋은 방법은 무엇입니까 컴파일하지 않는 이유는 무엇입니까?

답변

2
this.route.paramMap 
    .switchMap((params:ParamMap) => { 
    const idAsString = params.get('id'); 
    return idAsString ? 
     Observable.from(this.heroService.getHero(+idAsString)) : 
     Observable.of(new Hero()); 
    }) 
    .subscribe(hero => this.hero = hero); 

또는이 같은 노선이 경로로부터 링크, 당신은 스냅 샷이 사용하지 수 있다면 :

const idAsString = this.route.snapshot.paramMap.get('id'); 
if (idAsString) { 
    this.heroService.getHero(+idAsString).then(hero => this.hero = hero); 
} 
else { 
    this.hero = new Hero(); 
}