参考来源:https://www.angular.cn/tutorial/toh-pt4
ng generate service hero
ng generate service hero --module=app
1、英雄服务
import {Injectable} from '@angular/core';
import {Hero} from '../hero';
import {HEROES} from '../mock-heroes';
import {Observable, of} from 'rxjs';
import {MessageService} from './message.service';
@Injectable()
export class HeroService {
constructor(private messageService: MessageService) {
}
getHeroes(): Observable<Hero[]> {
this.messageService.add('HeroService: fetched heroes');
return of(HEROES);
}
}
2、消息服务
import {Injectable} from '@angular/core';
@Injectable()
export class MessageService {
messages: string[] = [];
add(message: string) {
this.messages.push(message);
}
clear() {
this.messages = [];
}
}
3、消息组件
import {Component, OnInit} from '@angular/core';
import {MessageService} from '../service/message.service';
@Component({
selector: 'app-messages',
templateUrl: './messages.component.html',
styleUrls: ['./messages.component.css']
})
export class MessagesComponent implements OnInit {
constructor(public messageService: MessageService) {
}
ngOnInit() {
}
}
4、消息模板
<div *ngIf="messageService.messages.length">
<h2> Messages</h2>
<button class="clear"
(click)="messageService.clear()">clear
</button>
<div *ngFor="let message of messageService.messages">{{message}}</div>
</div>
5、App模块添加服务依赖
import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {AppComponent} from './app.component';
import {HeroesComponent} from './heroes/heroes.component';
import {HeroDetailComponent} from './hero-detail/hero-detail.component';
import {MessagesComponent} from './messages/messages.component';
import {MessageService} from './service/message.service';
import {HeroService} from './service/hero.service';
@NgModule({
declarations: [
AppComponent,
HeroesComponent,
HeroDetailComponent,
MessagesComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [HeroService, MessageService],
bootstrap: [AppComponent]
})
export class AppModule {
}