marnaels marnaels - 5 months ago 33
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);;

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=' + + '&password=' + user.password;
headers.append('Content-Type', 'application/x-www-form-urlencoded');

this.baseApiUrl + '/oauth/access_token',
headers: headers

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

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

setCookie(accessToken: string): void {


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


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()