2016-03-02 26 views
6

我需要使用一個服務的多個實例。如何在服務中使用提供者?

通常當我使用組件此服務的一個實例,我寫的是這樣的:

@Component({ 
    selector: 'one-component', 
    providers: [provide("token1", {useClass: Service})], 
    template: ` 
     <h1>App</h1> 
    ` 
}) 
export class OneComponent { 
    constructor(@Inject('token1') service:Service) {} 
} 

但現在我需要使用服務2這項服務,我寫的是這樣的:

export class Service2 { 
    constructor(@Inject('token1') service:Service) {} 
} 

如你所知,它表明:

沒有提供

因爲Service2沒有providers: [provide("token1", {useClass: Service})]。但是我可以在哪裏添加它,因爲它沒有@Component

感謝

+0

那你在哪裏使用你的Service2呢? – Ludohen

+0

@Ludohen謝謝你的幫助,我在一個組件中使用Service2。 –

+0

然後你想做的事情肯定是可能的 – Ludohen

回答

0

我不認爲岡特的答案是完全正確的位置。 如果我正確理解了洪波苗的問題,這可以「輕鬆」實現。 如果您想要在每次注射中獲得新服務實例,則必須使用useFactory而不是useClass提供程序配置。

然後,如果你在Service2得到一個沒有提供錯誤"token1"這是因爲它不是正確的噴油器,兄弟姐妹或父母的OneComponent ...其中Service2注入配置。

編輯:

對於這個工作,你必須在根組件(例如)來定義ServiceService2提供商。在這種情況下,所有人都將共享相同的服務實例。

如果您想在每個組件中使用不同的實例,請在組件級別定義使用服務的提供程序。

@Component({ 
    providers: [Service, Service2], 
    // Other config props 
}) 
export class RootComponent { 
} 

@Component({ 
    // Config props 
}) 
export class OneComponent { 
    constructor(public service: Service) {} 
    methodx() { 
    this.service... 
    } 
} 

@Component({ 
    // Config props 
}) 
export class TwoComponent { 
    constructor(public service: Service2) {} 
    methodx() { 
    this.service... 
    } 
} 

@Injectable() 
export class Service2 { 
    constructor(public service: Service) { 
    } 
} 

使用@Inject('StringToken')是不是你做的最好的事情,是不推薦的方式。改爲使用Type標記(如上面的代碼中所做的那樣)。

資源:

+0

謝謝,我很快就會有支票! –

+0

根據你的代碼和我想要的,我有另一個'ThreeComponent',它也使用'Service',我想'OneComponent'和'ThreeComponent'使用不同的'Service'實例。這就是爲什麼我使用'Service'時添加令牌的原因。然後在'Service2'中,我沒有辦法使用'provider'作爲'Service'。 –

+0

'Service2'不需要任何特殊的東西,提供者在注入器樹中定義如上 – Ludohen

0

我已經在app.module.ts的供應商陣列宣佈兩項服務糾正了這個錯誤(使用服務B到服務A) 。

@NgModule({ 
    declarations: [...], 
    imports:  [...], 
    providers: [ 
     ServiceA, 
     ServiceB, 
    ], 
    bootstrap: [...], 
}) 
相關問題