I have a service.ts class with the following :
getData(username:string, password:string) {
let params: URLSearchParams = new URLSearchParams();
params.set('username', username);
params.set('password', password);
let requestOptions = new RequestOptions();
requestOptions.search = params;
return this._http.get(this._url,requestOptions).map((res:Response)=>res.status)
.catch((error: any) => {
if (error.status === 500) {
return Observable.throw(new Error(error.status));
}
else if (error.status === 400) {
return Observable.throw(new Error(error.status));
}
else if (error.status === 409) {
return Observable.throw(new Error(error.status));
}
else if (error.status === 406) {
return Observable.throw(new Error(error.status));
}
});
}
onCLick(myForm : NgForm) {
this._service.getData(this.userName, this.password).subscribe(resData => this.formStatus = resData,
resError => this.formStatus = resError);
if (this.formStatus === 400) {
this.router.navigateByUrl('/Home');
} else if (this.formStatus === 200) {
console.log(this.formStatus );
} else {
console.log(this.formStatus );
}
}
if (this.formStatus === 400) {
this.router.navigateByUrl('/Home');
} else if (this.formStatus === 200) {
console.log(this.formStatus );
} else {
console.log(this.formStatus );
}
How you debugging? Place console.log to catch block.
I think it's not good practice to check condition right after async execution.
This part executes async:
this._service.getData(this.userName, this.password).subscribe(resData => this.formStatus = resData,
resError => this.formStatus = resError);
And this part may not execute correctly, because this.formStatus
may not initialize yet.
if (this.formStatus === 400) {
this.router.navigateByUrl('/Home');
} else if (this.formStatus === 200) {
console.log(this.formStatus );
} else {
console.log(this.formStatus );
}
You have to check it inside error block.