Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 角度组件中的HTTP post回调_Javascript_Angular_Typescript - Fatal编程技术网

Javascript 角度组件中的HTTP post回调

Javascript 角度组件中的HTTP post回调,javascript,angular,typescript,Javascript,Angular,Typescript,我最近一直在学习Angular 4,并使用了“英雄之旅”教程 在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((he

我最近一直在学习Angular 4,并使用了“英雄之旅”教程

在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'))
    );
}
在我看来,如果出现错误,这个.heros.push(hero)仍然会激活,并且我们会将一个英雄错误地添加到组件的英雄阵列中。我如何配置它,以便在成功发布时,此.heros.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
方法的第二个参数接受错误事件处理程序。第一个参数将仅在请求成功完成(200OK)时调用。因此,不可能错误地添加英雄

这只是一个演示概念的示例。您需要按照自己的意愿处理相应的事件。例如,如果出现错误,需要通过警报消息或警报样式等通知用户。除此之外,
subscribe
方法最多可以接收三个参数:一个
next
函数、一个
error
函数和一个
complete
函数。特别是对于Http请求,在成功请求时调用
next
,在错误时调用
error
,在
next
函数后调用
complete
。另见:谢谢你的回复。很高兴看到你说的和我已经尝试过的相似。至少这意味着我走上了正确的道路。但是,错误仍然没有过滤回来。我认为这是因为第一个代码块似乎在处理错误,但没有让错误过滤器返回。正如指南所描述的:“下面的handleError()方法报告错误,然后返回一个无害的结果,这样应用程序就可以继续工作。”有没有办法保留handleError的功能,但仍然可以将其过滤掉?
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.");
        });
}