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.
rxjs 6
rxjs 5
What you return with
ErrorObservable
is up to youwith rxjs 6
Most of my issues were related to the imports, so here's the code that worked for me...
This will be the solution if you are facing errors like...
Use the catch operator
And handle the error like this:
Either
or