天天看點

【Angular】09依賴注入

​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>      
......
import { ListService } from '../serves/list.service';
@Component({
  selector: 'app-sthome',
  templateUrl: './sthome.component.html',
  styleUrls: ['./sthome.component.less'],
  providers: [ListService]
})
......