使用angular建立一個service

每天一隻喵發表於2017-09-22

1.建立一個以.service為字尾的ts檔案

2.在檔案中匯入

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

3.建立class並使用@Injectable()裝飾器

@Injectable()export class HeroService {}

4.新增方法到class中

5.在元件中匯入service服務

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

6.在@Component元件的後設資料底部新增providers陣列屬性

  providers: [HeroService]

7.在元件的class中的構造方法裡新增該服務

constructor(private heroService: HeroService) { }
8.使用this.heroService.方法就可以用service中的方法了

9.service的程式碼

import {Injectable} from '@angular/core';
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' }
];
@Injectable()
export class HeroService {
  getHeroes(): Promise<Hero[]> {
    return Promise.resolve(HEROES);
  }
  getHeroesSlowly(): Promise<Hero[]> {
    return new Promise(resolve => {
      // Simulate server latency with 2 second delay
      setTimeout(() => resolve(this.getHeroes()), 2000);
    });
  }
}

10.官方文件地址

https://angular.cn/tutorial/toh-pt4



相關文章