如何手动抛出可观察到的错误? [英] How to throw an observable error manually?

查看:53
本文介绍了如何手动抛出可观察到的错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个Angular应用程序,该应用程序中我通过HTTP进行如下调用:

I am working on an Angular app in which I am making a rest call through HTTP as below:

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;
        }
    });
}

基本上我希望我的组件得到响应&我的订阅通话中出现错误,即

Basically I want my component to get response & error in my subscribe call, i.e.

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总是返回成功,就像这样定义的.

but my API always returns success as it is defined that way.

如果response.success == 0,如何抛出错误消息,以便可以在我的订阅回调的error参数内部对其进行访问?

How can I throw an error message if response.success == 0, so that it will be accessed inside error argument of my subscribe callback?

推荐答案

if (response.success == 0) {
   throw Observable.throw(response);  
 } 

rxjs 6

Edit for rxjs 6:

if (response.success == 0) {
   throw throwError(response);  
 } 

这篇关于如何手动抛出可观察到的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆