簡體   English   中英

在Angular 2中使用Injector時沒有提供程序

[英]No provider while using Injector in Angular 2

首先,我有一個Context類和一個Singleton 我希望Context將Http和Events的實例提供給Singleton

import { Http } from 'angular2/http';
import { Injectable, Injector, Provider, provide } from 'angular2/core';
import { Events } from 'ionic-angular';

@Injectable()
export class Context{
    constructor(private http: Http, private events: Events){}
}

export class Singleton{
    private static INSTANCE: Singleton;

    private context: Context;

    constructor(){
        if(Singleton.INSTANCE){
            throw new Error();
        }
        let injector = Injector.resolveAndCreate([
            Https,
            Events
        ])
        this.context = injector.get(Context);
    }

}

但是,當我編譯檢查時。 出現“沒有提供者”的錯誤。 因此,如何添加提供者?

其次,如何在Singleton使用http和events? 我想Singleton中的this.http不起作用。

您還需要設置Context

let injector = Injector.resolveAndCreate([
        Https,
        Events,
        Context // <-------
    ])
    this.context = injector.get(Context);
}

話雖這么說,Angular2將為每個提供者保留一個實例,並且您不需要隱式地利用Injector類。

您不需要SINGLETON類。 您可以將Context實例直接注入到另一個組件或服務中:

@Component({
  (...)
  providers: [ Context ]
})
export class SomeComponent {
  constructor(private context:Context) {
  }
}

通過在組件的providers屬性中設置provider, context將成為該組件,其子組件以及它們將調用的所有服務的單例。

如果要為整個應用程序定義單例,請在引導應用程序時指定提供程序:

bootstrap(App, [ Context ]);

不要忘記從組件的providers屬性中刪除。

您還需要注意,進樣器已鏈接到組件。 有關更多詳細信息,此問題可以幫助您:

編輯

要在您的Singleton類中使用Http類,您需要定義HTTP_PROVIDERS而不是Http

let injector = Injector.resolveAndCreate([
        HTTP_PROVIDERS, // <-------
        Events,
        Context
    ])
    this.context = injector.get(Context);
    this.http = injector.get(Http); // <-------
}

更新

export class Singleton{
    private static INSTANCE: Singleton;

    constructor(private context:Context){
      console.log(context.http);
      console.log(context.events);
    }
}

原版的

    let injector = Injector.resolveAndCreate([
        Https,
        Events
    ])

創建一個僅知道提供者Https和`Events的新的獨立注入器。

您需要注入Angulars注入器,​​以便能夠從例如bootstrap(...)提供的提供程序中獲取實例bootstrap(...)

constructor(private injector:Injector){
  this.context = injector.get(Context);
}

暫無
暫無

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

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