Angular Tour of Heroes getHeroNo404,

  • 在完成6.HTTP后 , 然后我把getHero全局替换为了getHeroNo404()
  • 请求链接 http://127.0.0.1:4200/detail/1, 应该返回HeroService: did not find hero id=1, 实际是返回了id为11的英雄
  • 通过debug发现当请求http://127.0.0.1:4200/detail/1时, http.get返回的是一个id包含1的列表
  • 学到老活到老, 原来http.get返回的是一个包含参数的列表, 而不是完全的匹配
  • 修改方法, 修改map里的内容
getHeroNo404(id: number): Observable<Hero> {
    const url = `${this.heroesUrl}/?id=${id}`;
    return this.http.get<Hero[]>(url)
      .pipe(
        //原代码: map(heroes => heroes[0]),
        map(heroes => heroes.length === 1 ? heroes[0] : undefined),
        tap(h => {
          const outcome = h ? `fetched` : `did not find`;
          this.log(`${outcome} hero id=${id}`);
        }),
        catchError(this.handleError<Hero>(`getHero id=${id}`))
      );
  }