I've not been able to figure out what heroes is binding to inside of the subscribe method. When I get rid of the heroes type, somehow it is still displaying all of my heroes on the page. So if heroes has nothing to bind to inside of the service, how is it still able to display my heroes?
The following is the component that houses the subscribe method:
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 {
heroes: Hero[];
selectedHero: Hero;
onSelect(hero: Hero): void {
this.selectedHero = hero;
}
getHeroes(): void {
this.heroService.getHeroes()
.subscribe(heroes => this.heroes = heroes);
}
constructor(private heroService : HeroService) {}
ngOnInit() {
this.getHeroes();
}
}
And this is the hero service code:
import { Injectable } from '@angular/core';
import { Hero } from './heroes/hero';
import { HEROES } from './heroes/mock.heroes';
import { Observable, of } from 'rxjs';
import { HeroesComponent } from './heroes/heroes.component';
@Injectable({
providedIn: 'root'
})
export class HeroService {
getHeroes(): Observable<Hero[]> {
return of(HEROES);
}
constructor() { }
}
So here is the strange part: if you delete
heroes: Hero[];
The heroes still get displayed. How is that possible if there is nothing for the subscribe method to bind into? If the subscribe method is not binding into heroes, then how is heroes getting displayed onto the page?
All of the code has been done up to Subscribe in HeroesComponent in the tutorial of heroes @ https://angular.io/tutorial/toh-pt4#subscribe-in-heroescomponent
return of(HEROES)
. – Chief