How to throw observable error manually in angular2

2019-01-17 11:19发布

问题:

I am working on angular2 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;     
  }
);

but my api always returns success as it id defined that way.

So I want to know how can I throw error msg if response.success == 0 , so that it will be accessed inside error argument of my subscribe callback.

回答1:

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


回答2:

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



回答3:

Either

throw response;

or

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


回答4:

with rxjs 6

import { throwError } from 'rxjs';
throwError('hello');


回答5:

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


回答6:

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