我最近一直在学习Angular 4,并使用了“英雄之旅”教程here。
在Hero服务中,使用.pipe函数配置addHero方法,复制如下:
/** 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(英雄)仍然会被激活,并且我们会错误地将英雄添加到组件的英雄数组中。我如何配置它,以便在成功post时,this.heroes.push(英雄)完成,在这种情况下,抛出一个错误(4xx,5xx等),而不是显示一个警告(为了简单)?
发布于 2018-01-08 19:17:32
您可以尝试这样做:
add(name: string): void {
name = name.trim();
if (!name) { return; }
this.heroService.addHero({ name } as Hero)
.subscribe(hero => {
this.heroes.push(hero);
}, error => {
alert("Failed to get the hero.");
});
}在前面的代码段中,subscribe方法的第二个参数采用错误事件处理程序。并且第一个参数仅在请求成功完成(200OK)时被调用。因此,没有机会得到一个不正确的英雄添加。
https://stackoverflow.com/questions/48148860
复制相似问题