angular中的依赖注入
生活随笔
收集整理的這篇文章主要介紹了
angular中的依赖注入
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
依賴項(xiàng)是指某個(gè)類執(zhí)行其功能所需的服務(wù)或?qū)ο蟆R蕾図?xiàng)注入(DI)是一種設(shè)計(jì)模式,在這種設(shè)計(jì)模式中,類會從外部源請求依賴項(xiàng)而不是創(chuàng)建它們。
Angular 的 DI 框架會在實(shí)例化某個(gè)類時(shí)為其提供依賴。你可以使用 Angular DI 來提高應(yīng)用程序的靈活性和模塊化程度。
創(chuàng)建可注入服務(wù):
//在 src/app/heroes 目錄下生成一個(gè)新的 HeroService 類 ng generate service heroes/hero注意:
為了清晰和可維護(hù)性,建議你在單獨(dú)的文件中定義組件和服務(wù)。
如果你確實(shí)要將組件和服務(wù)合并在同一個(gè)文件中,則必須先定義服務(wù),再定義組件,這一點(diǎn)很重要。如果在服務(wù)之前定義組件,Angular 將返回運(yùn)行時(shí)的空引用錯(cuò)誤。
//src/app/heroes/hero.service.tsimport { Injectable } from '@angular/core';//@Injectable() 裝飾器會指定 Angular 可以在 DI 體系中使用此類。元數(shù)據(jù) providedIn: 'root' 表示 HeroService 在整個(gè)應(yīng)用程序中都是可見的。 @Injectable({ providedIn: 'root' }) export class HeroService {constructor() { }//要獲取英雄的模擬數(shù)據(jù)getHeroes() { return HEROES; } }注入服務(wù)
將依賴項(xiàng)注入組件的 constructor() 中
//src/app/heroes/hero-list.component import { HeroService} from '../app/heroes/hero.service'; @Component({selector: 'emr-inpatient-diagnosis-editor',templateUrl: './inpatient-diagnosis-editor.component.html',styleUrls: ['./inpatient-diagnosis-editor.component.scss'], }) export class InpatientDiagnosisEditorComponent{constructor(private heroService: HeroService) }再其他服務(wù)中使用這些服務(wù)
當(dāng)某個(gè)服務(wù)依賴于另一個(gè)服務(wù)時(shí),請遵循與注入組件相同的模式。在這里,HeroService 要依靠 Logger 服務(wù)來報(bào)告其活動。
import { Injectable } from '@angular/core'; import { HEROES } from './mock-heroes';//導(dǎo)入Logger服務(wù) import { Logger } from '../logger.service';@Injectable({providedIn: 'root'}) export class HeroService {//在constructor中注入Logger服務(wù)constructor(private logger: Logger) { }getHeroes() {this.logger.log('Getting heroes ...');return HEROES;} }總結(jié)
以上是生活随笔為你收集整理的angular中的依赖注入的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: angular ng-container
- 下一篇: angular @ViewChild使用