Service 服务
service: 服务,angular认为:组件时与用户交互的一种对象,其中的内容都应该与用户的操作有关系的;而与用户操作无关的内容都应该剥离出去,放在“服务对象”中,为组件服务;例如:日志记录、计时功能、数据库服务器的访问......
依赖注入式创建对象,无需new,只需要声明依赖;服务提供者就会创建被依赖的对象,注入给服务需要者
创建服务对象的步骤
- 创建服务对象并指定服务提供者
// log.service.ts
import { Injectable } from "@angular/core";
// 所有的服务对象都是 “可被注入的”
// 方式1:创建的服务对象是“单例的”--无论多少个组件使用该服务,只创建一个实例
@Injectable({
providedIn: 'root' // 服务提供者
// 指定当前服务对象在“根模块”中提供--AppModule
})
// 方式2:等同于方式1
// app.module.ts
providers:[LogService]
// 方式3:每个组件对应的服务对象都是新建出来的
@Injectable()
exports class LogService(){}
@Components({
......
providers:[LogService] // 组件级服务对象
})
export class LoginComponents{}
export class LogService { // 服务对象
doLog(action:unknown){
let uname = 'admin4'
let time = new Date().getTime()
console.log(`管理员:${uname} 时间:${time} 动作${action}`);
}
}
- 在组件中声明依赖,服务提供者就会自动注入进来,组件直接使用服务对象即可
export class XxComponent{
log:LogService
constructor(log:LogService){
// 此处的log变量就会被注入为LogService实例
this.log = log
}
doAdd(){
console.log('正在执行数据库的添加...');
let action = '添加了新的商品 xxx'
this.log.doLog(action)
}
}