使用angular創建一個service

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



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章