首页 > 解决方案 > 通过 Chrome 使用 Angular 12 在 TypeScript 中调试 API

问题描述

我无法从 SO 中找到解决方案。

如何调试和检查hello下面?

getHero(): void {
  const id = parseInt(this.route.snapshot.paramMap.get('id') !, 10);
  this.heroService.getHero(id)
    .subscribe(hero => this.hero = hero);
}

https://stackblitz.com/angular/roynrxqmenv?file=src%2Fapp%2Fhero-detail%2Fhero-detail.component.ts

它显示undefined如下,但实际上具有价值, 在此处输入图像描述

任何想法?

同样,如何调试getHero下面的返回值。以下h不显示任何内容。

getHero(id: number): Observable<Hero> {
  const url = `${this.heroesUrl}/${id}`;
  return this.http.get<Hero>(url).pipe(
    tap(h => this.log(`fetched hero id=${id}`)),
    catchError(this.handleError<Hero>(`getHero id=${id}`))
  );
}

https://stackblitz.com/angular/roynrxqmenv?file=src%2Fapp%2Fhero.service.ts

标签: angulartypescript

解决方案


最简单的方法是将单行语句包装在回调函数中{}

getHero(): void {
  const id = parseInt(this.route.snapshot.paramMap.get('id') !, 10);
  this.heroService.getHero(id)
    .subscribe(hero => {
      // debugger;
      this.hero = hero;
    });
}

这将允许您在浏览器中的正确位置放置断点。

你也可以debugger在里面放一个,以防万一。


推荐阅读