我只是通過閱讀v.4.0的教程來學習Angular。我剛剛參加了該教程的Section 6(路由),並且我理解了subscribe
方法。我會很樂意爲你解釋一下。有人可以解釋Angular訂閱方法
據我所知,ngOnInit()
被調用一次,這就是爲什麼我們在這裏使用subscribe()
。但是,什麼事件使subscribe()
被觸發?只有當再次請求包含特定HeroDetailComponent
的頁面時纔會觸發它。爲了我的理解,它必須附加到ActivatedRoute.params上的某種'onChange'事件,並在用戶請求同一頁面時觸發(包含HeroDetailComponent
)。
一旦ActivatedRoute.params
改變會發生什麼呢?我的意思是 - 如果ngOnInit()
只執行一次,this.hero
如何分配一個新值。我很好奇它是如何知道執行this.heroService.getHero(+params['id'])
並將返回值分配給this.hero
?從教程here
// mock-heroes.ts
export const HEROES: Hero[] = [
{ id: 11, name: 'Mr. Nice' },
{ id: 12, name: 'Narco' },
{ id: 13, name: 'Bombasto' },
{ id: 14, name: 'Celeritas' },
{ id: 15, name: 'Magneta' },
{ id: 16, name: 'RubberMan' },
{ id: 17, name: 'Dynama' },
{ id: 18, name: 'Dr IQ' },
{ id: 19, name: 'Magma' },
{ id: 20, name: 'Tornado' }
];
// hero.service.ts
@Injectable()
export class HeroService {
getHeroes(): Promise<Hero[]> {
return Promise.resolve(HEROES);
}
getHero(id: number): Promise<Hero> {
return this.getHeroes()
.then(heroes => heroes.find(hero => hero.id === id));
}
// hero-detail.component.ts
@Component({...})
export class HeroDetailComponent implements OnInit{
constructor(
private heroService: HeroService,
private route: ActivatedRoute,
private location: Location
) {}
ngOnInit(): void {
this.route.params
.switchMap((params: Params) => this.heroService.getHero(+params['id']))
.subscribe(hero => this.hero = hero);
}
編輯
完整的源代碼: 我剛剛發現了一個great article如果有人有問題理解這些概念,這可能是有用的。
請參閱:http://xgrommx.github.io/rx-book/content/observable/observable_instance_methods/subscribe.html和https://xgrommx.github.io/rx-book/content/getting_started_with_rxjs/creating_and_querying_observable_sequences/ creating_and_subscribing_to_simple_observable_sequences.html – wannadream