James James - 8 months ago 67
AngularJS Question

Http Get catch is not working in angular 2

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


My component.ts class is :

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


Here on running the page, even though the response is an error with status = 400, while debugging it is not entering the catch block of service.ts initially (after the server hit), instead it moves to the component.ts, in the function *onClick()*and then after execution out there entering the catch block, which look weird for me. I expect the catch block to be executed and not the return statement as there is an error.
P.S: formStatus in referring two-way binding from the form.

and thus the

if (this.formStatus === 400) {
this.router.navigateByUrl('/Home');
} else if (this.formStatus === 200) {
console.log(this.formStatus );
} else {
console.log(this.formStatus );
}


The above part of code is not working as the status is not set.

Answer Source

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.

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