Http Get catch 在 angular 2 中不起作用

Http Get catch is not working in angular 2

我有一个 service.ts class,其中包含以下内容:

getData(username:string, password:string) {

    let params: URLSearchParams = new URLSearchParams();
    params.set('username', username);
    params.set('password', password);


    let requestOptions = new RequestOptions();
    requestOptions.search = params;
    return  this._http.get(this._url,requestOptions).map((res:Response)=>res.status)
   .catch((error: any) => {
                if (error.status === 500) {
                    return Observable.throw(new Error(error.status));
                }
                else if (error.status === 400) {
                    return Observable.throw(new Error(error.status));
                }
                else if (error.status === 409) {
                    return Observable.throw(new Error(error.status));
                }
                else if (error.status === 406) {
                    return Observable.throw(new Error(error.status));
                }
            });
}

我的 component.ts class 是:

    onCLick(myForm : NgForm) {
    this._service.getData(this.userName, this.password).subscribe(resData => this.formStatus = resData,
    resError => this.formStatus = resError); 
    if (this.formStatus === 400) {
    this.router.navigateByUrl('/Home');
    } else if (this.formStatus === 200) {
    console.log(this.formStatus );
    } else {
       console.log(this.formStatus );
    }
  }

在 运行 页面上,即使响应是状态为 400 的错误,在调试时它也没有进入 catch 块=]service.ts 最初(在服务器命中之后),而是移动到 component.ts,在函数 *onClick()*and然后在执行后进入 catch 块,这对我来说看起来很奇怪。我希望执行 catch 块而不是 return 语句,因为存在错误。 P.S: formStatus 从表单引用双向绑定。

因此

if (this.formStatus === 400) {
    this.router.navigateByUrl('/Home');
    } else if (this.formStatus === 200) {
    console.log(this.formStatus );
    } else {
       console.log(this.formStatus );
    }

由于未设置状态,上述部分代码无法正常工作。

你是怎么调试的?放置 console.log 以捕获块。

我认为在异步执行后立即检查条件不是一个好习惯。

这部分执行异步:

this._service.getData(this.userName, this.password).subscribe(resData => this.formStatus = resData,
    resError => this.formStatus = resError); 

并且这部分可能无法正确执行,因为this.formStatus可能还没有初始化。

if (this.formStatus === 400) {
this.router.navigateByUrl('/Home');
} else if (this.formStatus === 200) {
console.log(this.formStatus );
} else {
   console.log(this.formStatus );
}

你必须在错误块中检查它。