Angular 2.0 基础:服务

什么是服务(Service)

在Angular 2 中我们提到的服务 service 一般指的是 哪些能够被其他组件或者指令调用的 单一的,可共享的 代码块。当然,通过服务可以将数据和组件分开,这样就可以实现更多的组件共享服务数据,服务能够使我们提高代码的利用率,方便组件之间共享数据和方法,方便测试和维护。在Angualr 文档中我们能看到这样的描述:

Multiple components will need access to hero data and we don't want to copy and  paste the same code over and over. Instead, we'll create a single reusable data service and learn to inject it in the components that need it.

Refactoring data access to a separate service keeps the component lean and focused on supporting the view. It also makes it easier to unit test the component with a mock service.

当我们用服务将数据和组件分开,数据的使用者无需知道数据是怎么获取的,Service 服务可以从任何地方获取数据。而同时因为访问数据从组件中移出,我们可以在服务中随时更改数据的访问方式,而无需对组件进行任何修改。

如何创建服务

首先,我们要创建一个 xxx.service.ts 的文件(当然,我们要遵循文件命名规则: 服务名:小写的基本名加上.service的后缀。如果服务名包含多个单词我们就把基本名部分写成中线形式  xxx-xxx.service.ts)

import {Injectable} from '@angular/core';
@Injectable()
export  class HeroService{
    
}

 由上code 可以看出,我们要在服务中注入依赖【但此时还没有注入任何依赖】

获取数据: 即添加一个桩方法

  @Injectable()
 export class HeroService {
      getHeroes(): void {} // stub
}

模拟数据

上面我们提到,数据不该和组件在一起,他应该被分离出来,然后通过Service 来获取数据。所以很显然数据集不能再组件里,也不会在Service里。我们先来用一个mock 文件来模拟数据。

即:新建一个文件 mock-heroes.ts

首先我我们要先建一个model 类:Hero(hero.ts);然后通过这个model来创建数据

hero.ts:

export class Hero{
    id:number;
    name:string;
}

mock-heroes.ts 

import { Hero } from './hero';

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'}
];

在mock-heroes 中我们导出来常量HEROES 以便于在其他地方导入。如Service

将数据导入Service

在hero.service.ts中,我们导入常量HEROES,并在getHeroes()中返回。即,我们在服务中获取来所需要的数据。

import { Injectable } from '@angular/core';

import { Hero } from './hero';
import { HEROES } from './mock-heroes';

@Injectable()
export class HeroService {
  getHeroes(): Hero[] {
    return HEROES;
  }
}

使用HeroService 服务 

现在我们可以在不同的组件中使用服务HeroService。首先我们要在需要使用该服务的组件中引用该服务;

然后我们可以通过new 的方式去将其实例化。即:

import { HeroService } from './hero.service';
heroService = new HeroService(); // don't do this

但是一般不这样使用。因为这样的话如果我们改变了HeroService 的构造函数,就同时也要找出创建过此服务的代码。然后修改他。

所以我们要通过 注入 HeroService 来代替New 操作。

首先我们要先添加一个构造函数,平定义一个私有属性

constructor(private heroService: HeroService /* 定义一个私有属性heroService,然后标记注入HeroService*/) { } 

然后当创建组件时,要先提供一个HeroService 的实例。即,我们需要注册一个HeroService 的providers,以便于注入器创建HeroService 实例。

即,当创建组件时,也会创建一个HeroService 的实例,然后组建会使用服务来获取数据。

我们可以通过 this 直接条用服务中的方法并获得数据。也可以通过封装方法来获取

如:

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

然后通过生命周期钩子来调用 这个封装好的get 方法(我们只要实现来Angular 的生命周期钩子,它就会主动调用这个钩子)

生命周期钩子:

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

export class AppComponent implements OnInit {
  ngOnInit(): void {
//this.getHeroes() } }

异步服务

上面的数据是我们通过模拟数据而创建的一个静态的本地数据。但是实际项目中我们一般是要通过活http 来异步调用远端服务商的数据

然后我们就要使用异步技术 Promise,即当他异步获取数据成功后会调用我们的回调函数

即在服务中,我们要将getHeroes 方法改为

getHeroes(): Promise<Hero[]> {
  return Promise.resolve(HEROES);
}  

在组件中,我们要把方法改为基于Promise 的格式

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

 即获取heroes 后将heroes 赋值给当前变量

总结:

  1. 之所以用Service 是为了将数据和组建分开。然后通过Service 获取数据,可以在不同的组件中使用同一个Service。实现数据共享。
  2. Service可以通过任意的方式去获取数据,使用者,即组件无需知道数据是从和而来,怎么获取的。
  3. 通过new 进行实例化的话,如果工作函数发生变化,可能会带来更多的修改任务,而引入注入可以很好的解决这个问题;通过注入,构造函数只需声明哟个私有的属性,然后标记注入。注入器会根据providers创建实例
  4. 构造函数是为了简单的初始化工作而设计,
  5. 生命周期钩子ngOnInit:Angular 会主动调用生命周期钩子,可以通过这一特点实现方法的调用
  6. 异步服务,要通过Promise来实现异步回调函数的调用

Demo的主要 Code:

hero.servie.ts

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);
  }
  // See the "Take it slow" appendix
  getHeroesSlowly(): Promise<Hero[]> {
    return new Promise<Hero[]>(resolve =>
      setTimeout(resolve, 2000)) // delay 2 seconds
      .then(() => this.getHeroes());
  }
}

 app.component.ts

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

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

@Component({
  selector: 'my-app',
  template: `
    <h1>{{title}}</h1>
    <h2>My Heroes</h2>
    <ul class="heroes">
      <li *ngFor="let hero of heroes"
        [class.selected]="hero === selectedHero"
        (click)="onSelect(hero)">
        <span class="badge">{{hero.id}}</span> {{hero.name}}
      </li>
    </ul>
    <my-hero-detail [hero]="selectedHero"></my-hero-detail>
  `,
  styles: [`
    .selected {
      background-color: #CFD8DC !important;
      color: white;
    }
    .heroes {
      margin: 0 0 2em 0;
      list-style-type: none;
      padding: 0;
       15em;
    }
    .heroes li {
      cursor: pointer;
      position: relative;
      left: 0;
      background-color: #EEE;
      margin: .5em;
      padding: .3em 0;
      height: 1.6em;
      border-radius: 4px;
    }
    .heroes li.selected:hover {
      background-color: #BBD8DC !important;
      color: white;
    }
    .heroes li:hover {
      color: #607D8B;
      background-color: #DDD;
      left: .1em;
    }
    .heroes .text {
      position: relative;
      top: -3px;
    }
    .heroes .badge {
      display: inline-block;
      font-size: small;
      color: white;
      padding: 0.8em 0.7em 0 0.7em;
      background-color: #607D8B;
      line-height: 1em;
      position: relative;
      left: -1px;
      top: -4px;
      height: 1.8em;
      margin-right: .8em;
      border-radius: 4px 0 0 4px;
    }
  `],
  providers: [HeroService]
})
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;
  }
}

app.module.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule }   from '@angular/forms';

import { AppComponent }  from './app.component';
import { HeroDetailComponent } from './hero-detail.component';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule
  ],
  declarations: [
    AppComponent,
    HeroDetailComponent
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

  

 

  

原文地址:https://www.cnblogs.com/taoyoung/p/6194666.html