2017-02-13 77 views
7

我可以這樣做:角2:房產注入,而不是構造函數注入

export class BaseComponent { 
protected config: IConfig; 

@Inject(AppConfig) protected appConfig: AppConfig; 

constructor() 
{ 
    this.config = this.appConfig.getConfig();  
} 

,而不是這樣的:

export class BaseComponent { 
config: IConfig; 

constructor(
    private appConfig: AppConfig, 
    ) 
{ 
    this.config = appConfig.getConfig();  
} 

的目標是簡化構造函數簽名的,因此所有子組件不需要在其構造函數中指定appConfig。所以,從BaseComponent繼承的組件看起來像這樣:

@Component({ 
    selector: 'sport-templates', 
    templateUrl: 'templates.component.html', 
    styleUrls: [ 'templates.component.scss' ], 
    encapsulation: ViewEncapsulation.None 
}) 
export class SportTemplates extends BaseComponent implements OnInit { 

    constructor() { 
     super(); 
    } 

,而不是像這樣:

@Component({ 
    selector: 'sport-templates', 
    templateUrl: 'templates.component.html', 
    styleUrls: [ 'templates.component.scss' ], 
    encapsulation: ViewEncapsulation.None 
}) 
export class SportTemplates extends BaseComponent implements OnInit { 

    constructor(appConfig: AppConfig) { 
     super(appConfig); 
    } 
+0

你有沒有發現用於構造器注入的最佳解決方案? – PaladiN

+0

我在這裏找到了我的問題的答案: https://stackoverflow.com/questions/42461852/angular-2-inject-service-manually謝謝。 –

回答

0

不,你不能做到這一點。 當構造函數被調用時,將注入注入服務

目標是簡化構造函數簽名。

沒有必要簡化構造函數簽名。爲了便於閱讀,您可以將它們寫入多行。

使所有子組件無需在其 構造

指定的AppConfig在你的情況下,只有繼承你的類訪問類。但是,如果您的意思是組件中使用的子組件,則它們無法訪問父組件中的變量。你需要通過他們。

修訂

this.config總是在繼承組件是可見的。不需要在SportTemplates組件中再次注入appConfig

+0

謝謝你的回覆。我在我的問題中加了一點澄清。 –

+0

@NikolaYankov更新回答問題 –

0

你可以這樣做:

myService: MyService = this.injector.get(MyService); 
constructor(private injector:Injector) {} 

注射器是@角/核心

+0

雖然它的工作,它看起來並不像真正的方式。更像服務定位器模式。儘管我不得不承認這種差異很微妙。 – XOR