1

I am trying out the Anuglar Heroes Tutorial for Typescript. While trying out the services the following code is working:

getHeroes() { 
    this.heroService.getHeroes().then(heroes => this.heroes = heroes); 
}

But when I change to code the following it is not working

getHeroes(){
    this.heroService.getHeroes().then(function (heroes:Hero[]) {
      this.heroes = heroes;
    })
}

I am getting the following error:

Unhandled Promise rejection: this is null ; Zone: angular ; Task: Promise.then ; Value: TypeError: this is null
this.heroes = heroes;

I have defined heroes inside the class as

heroes: Hero[];
0

2 Answers 2

1

That's because you lose the scope for this when you use a normal function instead of the arrow function.

You can use the Function.prototype.bind function:

getHeroes(){
    this.heroService.getHeroes().then(function (heroes:Hero[]) {
      this.heroes = heroes;
    }.bind(this));
}

If you prefer not to use the fat arrow function.

Sign up to request clarification or add additional context in comments.

1 Comment

Just to understand the basics I was playing around. This clears it
0

An arrow function expression has a shorter syntax compared to function expressions and lexically binds the this value (does not bind its own this, arguments, super, or new.target). Arrow functions are always anonymous. These function expression are best suited for non-method functions.

So this in below function is bind to the this of the callback functoin

getHeroes(){
    this.heroService.getHeroes().then(function (heroes:Hero[]) {
      this.heroes = heroes;
    })
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.