转载自 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
) {}
}