2017-01-12 53 views
1

我很清楚如何將服務注入到angular2中。我們可以在模塊級別或組件級別提供服務。將組件特定的值注入到Angular2服務中

我希望在該服務被注入到我的組件之前注入一個特定的屬性到服務。有問題的財產依賴於我的組件。 Angular 2中如何實現這一點?

實施例:

@Injectable() 
export class MyService { 
    constructor(myProperty: String) { 
    setSomethingUsingMyProperty(myProperty) 
    } 
} 

@Component(..., {providers: [MyService] }) 
export class MyComponent { 
    constructor(myService: MyService) { 
    myService.doSomething() 
    } 
} 

如果我提供上覆模塊中的屬性,那麼我相信Angular2可以注入屬性,如果我包括@Inject指令。但是如何在組件級別上實現呢?

回答

3

您可以提供,並以字符串名稱注入像

@Injectable() 
export class MyService { 
    constructor(@Inject('someName') myProperty: String) { 
    setSomethingUsingMyProperty(myProperty) 
    } 
} 
@Component({..., 
    providers: [MyService, {provide: 'someName', useValue: 'someValue'}] }) 
export class MyComponent { 
    constructor(myService: MyService) { 
    myService.doSomething() 
    } 
} 
+0

我曾推測,使用'useValue'將只適用於MyComponent的提供,例如,如果MyComponent的構造要求注射'someName'。如何解決MyService的DI需求?如果我將一個組件MySecondComponent注入到MyComponent中,那麼會發生什麼情況?MyComponent已經爲不同的值提供了'someName'給自己?順便感謝您的支持。 –

+1

如果你在'@ NgModule'而不是'@ Component'上提供'MyService',這是行不通的。當DI創建一個提供程序的實例時,它會從同一個注入器的其他提供程序(在我的答案中是組件注入器)開始,如果它沒有找到提供程序,它會查看父組件注入器, AppComponent'。如果在那裏找不到提供者,它會查找'@ NgModule'提供的提供者。在我的答案。提供者被發現在它尋找它的第一個位置並被注入。您不能注入除父母之外的其他組件。 –

+1

當父母提供'someName'但當前組件沒有,那麼根據上述規則,它將在DI尋找它的第二個位置上找到它。 –