How to throw an observable error manually?

后端 未结 8 1469
慢半拍i
慢半拍i 2020-12-02 16:35

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.a         


        
相关标签:
8条回答
  • 2020-12-02 16:59

    with rxjs 6

    import { throwError } from 'rxjs';
    throwError('hello');
    
    0 讨论(0)
  • 2020-12-02 17:00
    if (response.success == 0) {
       throw Observable.throw(response);  
     } 
    

    Edit for rxjs 6:

    if (response.success == 0) {
       throw throwError(response);  
     } 
    
    0 讨论(0)
  • 2020-12-02 17:01

    rxjs 6

    import { throwError } from 'rxjs';
    
    if (response.success == 0) {
      return throwError(response);  
    }
    

    rxjs 5

    import { ErrorObservable } from 'rxjs/observable/ErrorObservable';
    
    if (response.success == 0) {
      return new ErrorObservable(response);  
    }
    

    What you return with ErrorObservable is up to you

    0 讨论(0)
  • 2020-12-02 17:02

    Here is the official example (that emits number 7 and then error 'oops!'):

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

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

    0 讨论(0)
  • 2020-12-02 17:05

    Use the catch operator

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

    And handle the error like this:

    private handleError(error: Response) {
        console.error(error); // log to console instead
        return Observable.throw(error.json().error || 'Server Error');
    }
    
    0 讨论(0)
  • 2020-12-02 17:10

    Most of my issues were related to the imports, so here's the code that worked for me...

    import {_throw} from 'rxjs/observable/throw';
    login(email, password) {
    ...
        return this.http.post(`${this._configService.getBaseUrl()}/login`, body, options)
        .map((res: any) => {
    ...
            if (response.success == 0) {
               _throw(response);  
            } else if (response.success == 1) {
    ...
            }
        });
    }
    

    This will be the solution if you are facing errors like...

    ERROR TypeError: WEBPACK_IMPORTED_MODULE_2_rxjs_Observable.Observable.throw is not a function

    0 讨论(0)
提交回复
热议问题