Angular 注入服务 - angular 基础教程

转载自 http://www.ngui.cc/news/show-114.html

新建服务

ng g s mail

在命令行窗口运行以上命令后,将输出以下内容:

installing service create src/app/mail.service.spec.ts 
create src/app/mail.service.ts 
WARNING Service is generated but not provided, it must be provided to be used

即执行上述操作后,创建了两个文件:

  • mail.service.spec.ts - 用于单元测试

  • mail.service.ts - 新建的服务

除此之外,WARNING Service is generated but not provided,... 表示执行上述操作后,Angular CLI 只会帮我们创建 MailService 服务,不会自动帮我们配置该服务。

配置服务

import {MailService} from "./mail.service"; 
@NgModule({
  ...
  providers: [MailService],
  bootstrap: [AppComponent]
}) export class AppModule { }

更新服务

import { Injectable } from '@angular/core'; 
@Injectable() 
export class MailService {
  message: string ='该消息来自MailService'; 
 constructor() { }
}

使用服务

import { Component } from '@angular/core'; 
import {MailService} from "./mail.service"; 
@Component({
  selector: 'app-root',
  template: `
    <h3>{{title}}</h3>
    <div>
      <app-simple-form></app-simple-form>
      {{mailService.message}}
    </div>
  ` }) 
export class AppComponent {
  title = 'Hello, Angular'; 
 constructor(private mailService: MailService) {}
}

除了使用 constructor(private mailService: MailService) 方式注入服务外,我们也可以使用 Inject 装饰器来注入 MailService 服务:

import {Component, Inject} from '@angular/core'; 
@Component({...}) 
export class AppComponent {
  title = 'Hello, Angular'; 
 constructor(@Inject(MailService) private mailService) {}
}

不过对于 Type 类型(函数类型) 的对象,我们一般使用 constructor(private mailService: MailService) 方式进行注入。而 Inject 装饰器一般用来注入非 Type 类型的对象。

使用Inject装饰器

AppModule
@NgModule({
  ...
  providers: [
    MailService,
    {provide: 'apiUrl', useValue: 'https://jsonplaceholder.typicode.com/'}
  ],
  bootstrap: [AppComponent]
}) export class AppModule { }
AppComponent
@Component({
  selector: 'app-root',
  template: `
    <h3>{{title}}</h3>
    <div>
      <app-simple-form></app-simple-form>
      {{mailService.message}}
      <p>API_URL: {{apiUrl}}</p>
    </div>
  ` }) 
export class AppComponent {
  title = 'Hello, Angular'; 
 constructor( @Inject(MailService) private mailService,
    @Inject('apiUrl') private apiUrl
  ) {}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值