我可以這樣做:角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);
}
你有沒有發現用於構造器注入的最佳解決方案? – PaladiN
我在這裏找到了我的問題的答案: https://stackoverflow.com/questions/42461852/angular-2-inject-service-manually謝謝。 –