Saturday, May 25, 2024
 Popular · Latest · Hot · Upcoming
68
rated 0 times [  72] [ 4]  / answers: 1 / hits: 156044  / 8 Years ago, wed, november 9, 2016, 12:00:00

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?


More From » angular

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


Edit for rxjs 6:



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

[#60120] Tuesday, November 8, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
elliem

Total Points: 415
Total Questions: 117
Total Answers: 94

Location: American Samoa
Member since Fri, Aug 26, 2022
2 Years ago
;