还是angularjs2入门1-文件结构分析的源码,将app名称tutorial-step4-services
那时候,我们不得不等待服务器响应,并且在等待过程中我们无法阻塞用户界面响应, 即使我们想这么做(也不应这么做)也做不到,因为浏览器不会阻塞。我们不得不使用一些异步技术,我们将使用Promise。
import { Injectable } from '@angular/core'; import { Hero } from './hero'; import { HEROES } from './mock-heroes'; @Injectable() export class HeroService { getHeroes(): Promise<Hero[]> { return Promise.resolve(HEROES); } }
注入Injectable ,@Injectable()是必填的,代表元数据;注解一个Injectable组件,Injectable组件一般是服务类组件,单例模式。
创建mock-heroes,在任何文件都能引用。
2.根组件。我们写了一个带有初始化逻辑的ngOnInit
方法,Angular会在适当的时候调用它。 在这个例子中,我们通过调用getHeroes
来完成初始化。
export class AppComponent implements OnInit { title = 'Tour of Heroes'; heroes: Hero[]; selectedHero: Hero; constructor(private heroService: HeroService) { } getHeroes(): void { this.heroService.getHeroes().then(heroes => this.heroes = heroes); } ngOnInit(): void { this.getHeroes(); } onSelect(hero: Hero): void { this.selectedHero = hero; } }
ngOnInit 生命周期钩子。我们该在哪里调用getHeroes方法呢?在构造函数中吗? 不 !。多年的经验和惨痛的教训教育我们,应该把复杂的逻辑扔到构造函数外面去, 特别是那些需要从服务器获取数据的逻辑更是如此。
constructor构造器,声明heroService。
The constructor itself does nothing. The parameter simultaneously defines a private heroService property and identifies it as a HeroService injection site.
ngOnInit初始化事件,getHeroes方法用来获取数据。
As a result of our change toHeroService
,we're now settingthis.heroes
to a Promise rather than an array of heroes.
We have to change our implementation to@H_301_47@act on the Promise when it resolves. When the Promise resolves successfully,@H_301_47@thenwe will have heroes to display.
We pass our callback function as an argument to the Promise'sthenmethod: