angular学习008服务

参考来源: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 {
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值