angular6-service

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()
  }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值