providedIn: 'root'
指定 Angular 应该在根注入器中提供该服务,从而实现根注入器将服务注入,它就在整个应用程序中可用
providedIn:
- root :注入到AppModule,提供该服务,所有子组件都可以使用(推荐)
- null : 不设定服务作用域(不推荐)
- 组件名:只作用于该组件(懒加载模式)
//导入Injectable装饰器
import {
Injectable } from '@angular/core';
//使用Injectable装饰器声明服务
@Injectable({
//作用域设定,'root'表示默认注入,注入到AppModule里
providedIn: 'root'
})
export class ListService {
constructor() {
}
list:Array<string>=['Angular','React','Vue']
getList(){
return this.list
}
addList(str:string){
this.list.push(str)
}
}
import {
ListService } from '../serves/list.service';
constructor(private listService:ListService) {
}
list:Array<string> | undefined
ngOnInit(): void {
console.log('sthome-ngOnInit')
this.list = this.listService.getList()
}
// 渲染结构
<!-- 服务 -->
<p *ngFor="let item of list">{
{
item}}</p>
也可以使用 @Component
或 @Directive
内部的 providers: []
,为特定的组件子树提供服务,这也将导致创建多个服务实例(每个组件使用一个服务实例)
......
import {
ListService } from '../serves/list.service';
@Component({
selector: 'app-sthome',
templateUrl: './sthome.component.html',
styleUrls: ['./sthome.component.less'],
providers: [ListService]
})
......