angularjs2进阶教程4-创建可重用的服务数据

来源:互联网 发布:细说php第三版pdf 编辑:程序博客网 时间:2024/06/06 08:31

还是 angularjs2入门1-文件结构分析 的源码,将app名称tutorial-step4-services

1.创建服务hero.service.ts,能够公用获取英雄的数据
将来,我们打算从远端服务器上获取英雄数据。我们还没调用 http,但在后面的章节中我们会希望这么做。
那时候,我们不得不等待服务器响应,并且在等待过程中我们无法阻塞用户界面响应, 即使我们想这么做(也不应这么做)也做不到,因为浏览器不会阻塞。我们不得不使用一些异步技术,我们将使用 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 to HeroService, we're now setting this.heroes to a Promise rather than an array of heroes.

We have to change our implementation to act on the Promise when it resolves. When the Promise resolves successfully, then we will have heroes to display.

We pass our callback function as an argument to the Promise's then method:



0 0
原创粉丝点击