我的工作angular2的应用程序中,我想提出通过HTTP REST调用如下:如何在angular2中手动抛出可观察的错误?
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总是返回它的ID定义的方式成功。
因此,我想知道如果response.success == 0
,我怎么能抛出错误消息,以便它将被访问我的订阅回调的错误参数。
是什么身份代码你得到,我的意思是它可以是其他然后0? –
@MrJSingh设计API的人只会返回成功0或1来验证response.so我的操作是成功的,它会返回success = 1或者它会返回success = 0。现在我想抛出错误,如果成功是可能的吗? –
让我试试我的应用程序,从技术上讲它应该是可能的。 –