【发布时间】:2018-01-08 19:51:22
【问题描述】:
我最近一直在学习 Angular 4,并使用了“英雄之旅”教程here。
在 Hero 服务中,addHero 方法是使用 .pipe 函数配置的,复制如下:
/** POST: add a new hero to the server */
addHero (hero: Hero): Observable<Hero> {
return this.http.post<Hero>(this.heroesUrl, hero, httpOptions).pipe(
tap((hero: Hero) => this.log(`added hero w/ id=${hero.id}`)),
catchError(this.handleError<Hero>('addHero'))
);
}
这一切都很好 - 现在组件可以调用 this.heroService(heroObject)。然而,我遇到的问题是当它出错时会发生什么。是的,管道内的 catchError 处理它,但在我看来,该组件似乎不知道发生了什么。如果有 404 并且从未添加英雄怎么办?在组件中,通过以下方式添加英雄:
add(name: string): void {
name = name.trim();
if (!name) { return; }
this.heroService.addHero({ name } as Hero)
.subscribe(hero => {
this.heroes.push(hero);
});
}
在我看来,如果发生错误,this.heroes.push(hero) 仍然会激活,并且我们会错误地将英雄添加到组件的英雄数组中。我如何配置它,以便在成功发布时完成 this.heroes.push(hero),在这种情况下,抛出错误(4xx、5xx 等),而是显示警报(为简单起见)?
【问题讨论】:
-
这只是一个演示概念的示例。您需要按照您的意愿处理相应的事件。比如说,如果出现错误,需要通过警报消息或警报样式等方式通知用户。
标签: javascript angular typescript