我正在开发一个 Angular 应用程序,我正在通过 HTTP 进行休息呼叫,如下所示:
login(email, password) {
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let options = new RequestOptions({ headers: headers });
let body = `identity=${email}&password=${password}`;
return this.http.post(`${this._configService.getBaseUrl()}/login`, body, options)
.map((res: any) => {
let response: any = JSON.parse(res._body);
if (response.success == 0) {
Observable.throw(response); // not working
} else if (response.success == 1) {
console.log('success');
localStorage.setItem('auth_token', 'authenticated');
this.loggedIn = true;
return response;
}
});
}
基本上,我希望我的组件在我的订阅调用中得到响应和错误,即。
this._authenticateService.login(this.loginObj['identity'],this.loginObj['password']).subscribe(
(success)=>{
this.credentialsError=null;
this.loginObj={};
this._router.navigate(['dashboard']);
},
(error)=>{
console.log(error);
this.credentialsError=error;
}
);
但是我的 API 总是按照定义的方式返回成功。
如果是 response.success == 0
,我如何抛出错误消息,以便在订阅回调的错误参数中访问它?