2016-11-09 76 views
10

我的工作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

是什么身份代码你得到,我的意思是它可以是其他然后0? –

+0

@MrJSingh设计API的人只会返回成功0或1来验证response.so我的操作是成功的,它会返回success = 1或者它会返回success = 0。现在我想抛出错误,如果成功是可能的吗? –

+0

让我试试我的应用程序,从技术上讲它应该是可能的。 –

回答

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

我甚至没有使用此 –

+1

我不明白后得到它的成功回调,即使不使用它,你的意思是什么?你能解释给我吗?我测试了它,因为你有这种情况,只有当成功为0时,Observable才会抛出错误。 –

+0

我的意思是,如果我的响应返回任何东西,无论是错误还是成功,它总是会返回成功callback。我想要抛出错误在错误回调.. –

0

使用捕捉操作

this.calcSub = this.http.post(this.constants.userUrl + "UpdateCalculation", body, { headers: headers }) 
    .map((response: Response) => { 
     var result = <DataResponseObject>response.json(); 
     return result; 
    }) 
    .catch(this.handleError) 
    .subscribe(
     dro => this.dro = dro, 
    () => this.completeAddCalculation() 
    ); 

和处理这样的错误:

private handleError(error: Response) { 
    console.error(error); // log to console instead 
    return Observable.throw(error.json().error || 'Server Error'); 
} 
+0

我的API不会调用catch块。那是我遇到的问题。在我的回应中,我想检查某个条件,然后抛出错误或调用catch块。 –

+0

我已经得到这个错误有私人的HandleError(错误:响应)。 __WEBPACK_IMPORTED_MODULE_2_rxjs_Observable __ a.throw不是一个函数 在CatchSubscriber.selector –

3

要么

throw response; 

return Observable.throw(response); // not working 
+0

第二个它将是: '抛出Observable.throw(响应)' –

0

您可以使用:

import { ErrorObservable } from 'rxjs/observable/ErrorObservable'; 

if (response.success == 0) { 
    return new ErrorObservable(response); 
} 

ErrorObservable什么样的回报是你