我使用一個HTTP API,通過一個JSON返回應用程序級錯誤,其中status =='error'。Angular 4:如何正確處理應用程序級http錯誤爲可觀察錯誤?
在我的註冊服務,我這樣做:
return this.userService
.create(user)
.map(
json => {
console.log(json);
if (json.status=='error') {
console.log('error return throw');
return Observable.throw('Credentials mismatch or not existing');
}
const user = json.data as User;
return user;
},
err => {
console.log(err);
}
);
在我singUp.component,我這樣做:
onSubmit() {
// blahblah
this.si
.signUp(this.credentials.emailAddress, this.credentials.password, this.credentials.zipCode)
.subscribe(
user => {
console.log(user);
console.log(`SignUpComponent.onSubmit() found user.userId ${user.userId}`);
this.router.navigate(['signin']);
},
err => {
this.errorMessage = `*** SignUpComponent: Error while signing up {err}`;
console.error('*** SignUpComponent: Error while signing up', err);
this.resume();
//this.router.navigate(['signup']);
});
this.ngOnChanges();
}
不幸的是,當服務返回錯誤(與可觀測.throw())時,組件不會觸發err閉包,而是會將用戶參數傳遞Observable.throw作爲用戶閉包。
我希望我有err關閉被觸發。
我缺少什麼?
更新:這是我所得到的:
[Log] SigninService.signUp, zipCode=
[Log] {data: null, status: "error", message: "Error user create: - missing id API usage v1b3: Tu…ate\"}↵post: []↵.↵", ws: "v1b3: Tuesday, August 25th 2017 20h20 @ Tanger"}
[Log] error return throw
[Log] ErrorObservable {_isScalar: false, error: "Credentials mismatch or not existing", scheduler: undefined, _subscribe: function, …}
[Log] SignUpComponent.onSubmit() found user.userId undefined
什麼是你'.MAP()'d卷板機? – Aravind
它會查找API狀態以確保API返回全新用戶(當status =='success'時)。如果狀態等於「錯誤」(代表用戶帳戶未被創建),我希望我爲訂戶生成錯誤。 –
這工作? – Aravind