Search code examples
angulartypescriptarrow-functionsangular-observable

What is the correct interpretation of this arrow function subscribing an Observable in Angular?


I am following the official Angular tutorial: https://angular.io/tutorial/toh-pt4

As you can see there is one component class that subscribe on a service:

import { Component, OnInit } from '@angular/core';

import { Hero } from '../hero';
import { HeroService } from '../hero.service';

@Component({
  selector: 'app-heroes',
  templateUrl: './heroes.component.html',
  styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {

  selectedHero: Hero;

  heroes: Hero[];

  constructor(private heroService: HeroService) { }

  ngOnInit() {
    this.getHeroes();
  }

  onSelect(hero: Hero): void {
    this.selectedHero = hero;
  }

  getHeroes(): void {
    this.heroService.getHeroes()
        .subscribe(heroes => this.heroes = heroes);
  }
}

I have some doubts about the getHeroes() method of this component:

 getHeroes(): void {
    this.heroService.getHeroes()
        .subscribe(heroes => this.heroes = heroes);
  }

I know that my service returns an Observable<Hero[]> that I have to subscribe to because it is asynchronous.

The only thing that I can't completly understand is the inner expression (I think it is called lambda), this: heroes => this.heroes = heroes

What is the exact meaning of this expression?


Solution

  • You are correct, it is indeed a lambda, however they are more commonly referred to in js as arrow functions. They function the same way.

    That lambda equates to:

    (function (heroes) { return _this.heroes = heroes; });
    

    So it is expecting a parameter and then storing it in the local property.

    The Observable in your snippet could also be written:

    this.heroService.getHeroes()
       .subscribe((heroes: Hero[]) => {
          this.heroes = heroes;
       });
    

    Which is clearer of what it is returning.