Bhushan Gadekar Bhushan Gadekar - 1 year ago 130
TypeScript Question

How to throw observable error manually in angular2?

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._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) {
localStorage.setItem('auth_token', 'authenticated');
this.loggedIn = true;
return response;

basically I want my component to get response & error in my subscribe call.



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.

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

Note:- when you will subscribe to this Observable you will get this in success call back

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download