1.为什么创建服务
组件不应直接获取或保存数据,并且它们不应故意呈现假数据。他们应该专注于呈现数据并委托对服务的数据访问。
2.创建服务
使用angular CLI命令行创建一个名叫hero的服务
ng generate service hero
//简写 ng g s hero
该命令在src / app / hero.service.ts中生成HeroService类
src/app/hero.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class HeroService {
constructor() { }
}
3.引用
HeroService可以从任何地方获取数据,网络服务,本地存储或模拟数据源。
创建hero组件
ng generate compenent hero
在hero.component.ts文件中引入HeroService
import { HeroService } from '../hero.service'
...
export class HeroComponent implements OnInit {
constructor(private heroService: HeroService) { }
}
4.代码
hero.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class HeroService {
constructor() { }
public messages: string[] = [];
add(message: string) {
this.messages.push(message);
}
clear() {
this.messages = [];
return this.messages;
}
getHeroes() {
this.add('HeroService: fetched heroes');
return this.messages;
}
}
hero.component.html
<button (click)="getHeroes()">获取</button>
<button (click)="delete()">删除</button>
<ul>
<li *ngFor="let item of heroes">{{item}}</li>
</ul>
hero.component.ts
import { Component, OnInit } from '@angular/core';
import { HeroService } from '../hero.service'
@Component({
selector: 'app-hero',
templateUrl: './hero.component.html',
styleUrls: ['./hero.component.css']
})
export class HeroComponent implements OnInit {
constructor(private heroService: HeroService) { }
public heroes:any = []
ngOnInit() {
this.heroes = this.heroService.getHeroes();
}
getHeroes(): void {
this.heroService.getHeroes()
}
delete():void{
this.heroes = this.heroService.clear()
}
}