marnaels marnaels - 1 month ago 11
TypeScript Question

Success handler from http request does not call a function

I did successfully a post request with angular 2 http.

The problem that I have is when I try to execute a function from success handler. The error that I get from that is:

error_handler.js:48 EXCEPTION: this.setCookie is not a function


My component:

onSubmit(userData: any): void {
this.user = new UserData(userData);
this.services.getAccess(this.user).subscribe();
}


My services:

getAccess(user: UserData): any {
let headers = new Headers();
let client_id = 'fge432358768979fgwefg34f34';
let credentials = 'grant_type=password&client_id=' + client_id + '&client_secret=' + user.secretKey + '&username=' + user.email + '&password=' + user.password;
headers.append('Content-Type', 'application/x-www-form-urlencoded');

return this.http.post(
this.baseApiUrl + '/oauth/access_token',
credentials,
{
headers: headers
}
)
.map(this.handleSuccess)
.catch(this.handleError);
}

handleError(error: Response | any) {
console.log('error');
swal("Oops...", 'The informations you’ve entered doesn’t match any account. ', "error");
return Observable.throw(error);
}

handleSuccess(res: Response) {
if (res.status === 200) {
swal(
{
title: "Good job!",
text: "You have successfully logged in.",
timer: 2000,
type: "success",
showConfirmButton: false
}
);
this.setCookie(res.json().access_token)
}
}

setCookie(accessToken: string): void {
this.cookie.setForOneHour(accessToken);
}


}

Thanks in advance for any help you are able to provide.

Answer

You have to bind this to preserve the context.

You can use

  1. .map(this.handleSuccess.bind(this))
  2. use an arrow function

    .map(data => this.handleSuccess(data))
    

Remember that the same applies to the .catch()