Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to throw an observable error manually?

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

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

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

like image 860
Bhushan Gadekar Avatar asked Nov 09 '16 16:11

Bhushan Gadekar


People also ask

How do you throw an error in observable?

First, we create an observable using throwError . The first argument to the throwError is the error object. This error object is passed to the consumers when it raises the error notification. We, subscribe to it in the ngOnInit method.

Does error complete observable?

Bookmark this question. Show activity on this post.


2 Answers

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

Edit for rxjs 6:

if (response.success == 0) {    throw throwError(response);    }  
like image 187
Jorawar Singh Avatar answered Sep 27 '22 20:09

Jorawar Singh


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

like image 20
Kristjan Liiva Avatar answered Sep 27 '22 18:09

Kristjan Liiva