【发布时间】:2019-07-08 22:20:49
【问题描述】:
我正在开发/扩展 TOH。我有一个 add 方法想要将新英雄推送到数组上,然后将用户返回到列表中。
对 addHero 的调用结果以 JSON 英雄的形式在双刻度内返回,因此以字符串形式返回。
我已经阅读了很多似乎指向
的文章angular.toJson
or
.map(response=> response.JSON())
这些都不起作用。
这是我的 heros.component.ts 的摘录
add(name: string): void {
name = name.trim();
if (!name) { return; }
this.heroService.addHero({ name } as Hero)
.subscribe(hero =>
{
this.heroes.push(hero);
this.location.go('/Heroes');
}
);
}
和 hero.service.ts 这显然返回了一个 Hero 对象......
addHero (hero: Hero): Observable<Hero> {
return this.http.post<Hero>(this.heroesUrl, hero, httpOptions).pipe(
tap((hero: Hero) => console.log(`added hero w/ id=${hero.id}`)),
catchError(this.handleError<Hero>('addHero'))
);
}
返回时,结果成功推送到数组中,但用引号括起来。
这方面的 UI 证据是列表底部有一个空白条目,因为该最终数组元素上没有 .Name 属性。
如果我刷新页面,每个人都会被加载为 json。
简单的问题,但我似乎找不到答案。经历了许多涉及 ng2、php 等的 S/O 问题,但似乎没有一个解决 ng6,或者提供我可以带走的线索。如果他们这样做,我想念它。
【问题讨论】:
-
console.log(`added hero w/ id=${hero.id}`)的输出是什么? -
这就是问题所在。 hero.id 返回 null,因为唯一已初始化的属性是 hero.name。在这一点上,我什至不是财产。真正的问题是返回类型。
标签: json angular typescript