如何在angular2中手动抛出可观察的错误?

Bhu*_*kar 45 javascript typescript angular2-observables angular

我正在开发angular2 app,我正在通过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;
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

基本上我希望我的组件在我的订阅调用中获得响应和错误.

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;     
  }
);
Run Code Online (Sandbox Code Playgroud)

但我的api总是返回成功,因为它以这种方式定义.

所以我想知道如何抛出错误消息response.success == 0,以便在我的订阅回调的错误参数内访问它.

Cap*_*apK 66

rxjs 6

import { throwError } from 'rxjs';

if (response.success == 0) {
  return throwError(response);  
}
Run Code Online (Sandbox Code Playgroud)

rxjs 5

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

if (response.success == 0) {
  return new ErrorObservable(response);  
}
Run Code Online (Sandbox Code Playgroud)

你的回报ErrorObservable取决于你

  • 已接受的答案解决方案已在rxjs6中弃用.谢谢你,你的作品:) (7认同)

Jor*_*ngh 63

if (response.success == 0) {
   throw Observable.throw(response);  
 } 
Run Code Online (Sandbox Code Playgroud)

  • 这个答案已经过时了. (19认同)
  • 这将在错误回调中返回一个 Observable,这不是好的代码设计。相反,只需抛出您自己的错误对象“抛出{消息:'错误响应',值:响应}” (4认同)
  • 我不明白,即使不使用它是什么意思?你能给我解释一下吗?我按照您的情况对其进行了测试,并且仅当成功为 0 时 Observable 才会抛出错误。 (2认同)

Gün*_*uer 9

rxjs 5

throw response;
Run Code Online (Sandbox Code Playgroud)

要么

throw Observable.throw(response);
Run Code Online (Sandbox Code Playgroud)

  • 对于第二个,它将是:`throw Observable.throw(response)` (3认同)

小智 9

与rxjs 6

import { throwError } from 'rxjs';
throwError('hello');
Run Code Online (Sandbox Code Playgroud)

  • @Endrju 这是完全不同的。return throwError 将返回 observable,然后您可以使用 catchError 或内部 subsribe 处理它。如果你抛出 new Error('') 这将会冒泡并且不会在可观察对象内部处理...... (2认同)

Sin*_*dan 8

这是官方示例(发出数字 7,然后发出错误“哎呀!”):

import { throwError, concat, of } from 'rxjs';

const result = concat(of(7), throwError(new Error('oops!')));
result.subscribe(x => console.log(x), e => console.error(e));
Run Code Online (Sandbox Code Playgroud)

来自: https: //rxjs-dev.firebaseapp.com/api/index/function/throwError