我有一个service.ts类,其中包含以下内容:
Map<String, Customer> map = new HashMap<String, Customer>((int)Math.ceil(customerList.size() / 0.75));
customerList.forEach(x -> map.put(x.getId(), x));
我的component.ts类是:
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));
}
});
}
在运行页面时,即使响应是status = 400的错误,在调试时最初也没有进入 service.ts 的 catch 块(在服务器命中之后),而是在函数* onClick()*中移动到 component.ts ,然后在执行之后进入catch块,这看起来很奇怪。由于出现错误,我希望执行 catch 块而不是返回语句。 P.S: formStatus 从表单中引用双向绑定。
因此
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 );
}
}
由于未设置状态,上述部分代码无效。
答案 0 :(得分:1)
你如何调试?将console.log放在catch块中。
我认为在异步执行后立即检查条件并不好。
这部分执行异步:
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 );
}
你必须在错误块内检查它。