In switchMap return promise or the real object

In switchMap return promise or the real object

根据angular教程代码,我想使用 hero-details.component 来更新和创建英雄对象。

所以我添加了没有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));
}

但是我不知道如何在 hero-details.component 文件中处理。 在 switchMap 中,如果 Url 中没有 id 我想 return 一个新的英雄。但是,如果我有一个 id,我将 return 的服务称为 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);
  }

最好的方法是什么?

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);

或者,如果没有 link 从这条路线到这条路线,您可以只使用快照:

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