簡體   English   中英

Angular2 - 在組件外部使用依賴注入

[英]Angular2 - Use Dependency Injection outside Components

在我的應用程序中,我使用DI來傳遞有關UserLogged的信息,這些信息圍繞需要此類信息的不同組件。 這意味着我有一個像這樣的main.ts

import {AppComponent} from './app.component';
import {UserLogged} from './userLogged'

bootstrap(AppComponent, [UserLogged]);

並且需要使用UserLogged實例的UserLogged具有這樣的構造函數

constructor(private _user: UserLogged)

現在我想在簡單的TypeScript類(不是@Component )中使用相同的UserLogged實例。 這可能嗎? 換句話說,如果我在@Component之外,我是否可以獲得由DI注入的UserLogged的相同實例?

此構造函數也適用於服務(DI創建的其他類)

 bootstrap(AppComponent, [OtherClass, UserLoggged]);

 @Injectable()
 export class UserLogged {
   log(text) {
     console.log(text);
   }
 }

 @Injectable()
 export class OtherClass {
   constructor(private _user: UserLogged) {}
 }

 class SomeComponent {
   constructor(private otherClass:OtherClass) {
     this.otherClass._user.log('xxx');
   }
 }

如果你使用new SomeClass()創建這些類,那么你可以像它一樣注入它

 class SomeComponent {
   constructor(private _injector:Injector) {
     let userLog = this._injector.get(UserLogged);
     new SomeClass(userLog);
   }
 }

在你引導角度的文件中:

import { AppComponent } from './app.component';
import { UserLogged } from './userLogged';

declare global {
    var injector: Injector;
}

bootstrap(AppComponent, [UserLogged]).then((appRef) => {
    injector = appRef.injector;
});

在您的其他文件中:

import { UserLogged } from '../path/to/userLogged';

class TestClass {
    private userLogged: UserLogged;

    constructor() {
        this.userLogged = injector.get(UserLogged);
    }
}

為了能夠在類中使用依賴注入,您需要擁有一個裝飾器@Injectable

@Injectable()
export class SomeClass {
  constructor(private dep:SomeDependency) {
  }
}

Injectable這個名字並不是真的不言自明。 這是為了使類內注入成為可能(而不是另一類)。

需要從啟動調用的組件中看到SomeDependency類的提供程序。

有關依賴項注入和分層注入器的更多詳細信息,請參閱此問題:

我在這里采取瘋狂的猜測,但你的意思是說你想要使用providers : [UserLogged]注入類providers : [UserLogged] 如果是這種情況,這將有效

providers: [ provide(UserLogged, {useClass: UserLogged} ] 

將上面的內容添加到您的引導程序中,當您不想使用@Component時,您可以繼續使用

sample.ts

export class Sample{
   constructor(private ulog : UserLogged){}
}

在你的情況下,bootstrap將是:

import {provide}   from   'angular2/core';
import {HTTP_PROVIDERS}   from  'angular2/http';
bootstrap(AppComponent,[HTTP_PROVIDERS,provide(UserLogged, { useClass : UserLogged})]);

我添加了HTTP_PROVIDERS來演示如何添加多個提供程序。 干杯!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM