2016-07-22 23 views
0

我有一個服務,比如ServiceA,它執行大量的服務器通信工作。該服務在整個應用程序中被其他服務(包括ServiceB)大量使用。是否有一種方法可以註冊一次(即在App組件中),以便它可用於在子組件中註冊的所有服務?現在看來,我必須在每個調用它的服務旁邊註冊它。在哪裏註冊Angular 2服務,以便它可以在全球範圍內使用?

當我將ServiceA添加到AppComponent的viewProviders數組時,當注入器嘗試將ServiceB注入到子組件時,出現No provider for ServiceA!異常。

AppComponent

@Component({ 
    moduleId: module.id, 
    selector: 'app1', 
    viewProviders: [..., **ServiceA**],<--I WANT TO DO THIS SO ITS AVAILABLE EVERYWHERE 
    templateUrl: 'app.component.html', 
    directives: [...] 
}) 
export class AppComponent {} 

ServiceA

@Injectable() 
export class ServiceA { 
    constructor(http: Http) {} 
} 

ServiceB

@Injectable() 
export class ServiceB { 
    constructor(serviceA: ServiceA) {} 
} 

ChildComponent

@Component({ 
    moduleId: module.id, 
    selector: 'app1', 
    viewProviders: [ServiceB,**ServiceA**], <-AND I DON'T WANT TO HAVE TO DO THIS EVERY TIME 
    templateUrl: 'app.component.html', 
    directives: [...] 
}) 
export class ChildComponent { 
    constructor(private serviceB, ServiceB) {} 
} 
+2

使用提供者而不是提供者。 –

回答

1

注入服務的最佳方式是一樣的,你正在做,但不是通過在AppComponent的viewProviders注入它的,使用供應商的選擇。您只需將提供程序選項包含在根組件中,但必須記住在每個文件上導入服務並將其注入構造函數中。

@Component({ 
    moduleId: module.id, 
    selector: 'app1', 
    providers: [ServiceA], 
    templateUrl: 'app.component.html', 
    directives: [...] 
}) 
export class AppComponent {} 
+0

謝謝,這正是它! viewProviders僅供該組件視圖使用:http://stackoverflow.com/questions/35888434/what-are-viewproviders-in-angular-2-and-what-is-the-difference-b-w-providers-vs –

相關問題