2017-11-11 1 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がない場合、新しいHeroを返したいと思います。しかし、私は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(); 
} 
関連する問題