gpt4 book ai didi

javascript - Angular 组件中的 HTTP post 回调

转载 作者:行者123 更新时间:2023-12-03 02:44:40 24 4
gpt4 key购买 nike

最近在学习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 等),而是显示警报(为了简单起见)?

最佳答案

你可以试试这个:

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 方法的第二个参数采用错误事件处理程序。第一个参数只有在请求成功完成(200 Ok)时才会被调用。因此,不可能错误地添加英雄。

关于javascript - Angular 组件中的 HTTP post 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48148860/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com