使用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 {
    return Promise.resolve(HEROES);
  }
  getHeroesSlowly(): Promise {
    return new Promise(resolve => {
      // Simulate server latency with 2 second delay
      setTimeout(() => resolve(this.getHeroes()), 2000);
    });
  }
}

10.官方文档地址

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


 
  

你可能感兴趣的:(Angular学习,angular,Service)