角2:房产注入,而不是构造函数注入
我可以这样做:角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);
}
不,你不能做到这一点。 当构造函数被调用时,将注入注入服务。
目标是简化构造函数签名。
没有必要简化构造函数签名。为了便于阅读,您可以将它们写入多行。
使所有子组件无需在其 构造
指定的AppConfig在你的情况下,只有继承你的类访问类。但是,如果您的意思是组件中使用的子组件,则它们无法访问父组件中的变量。你需要通过他们。
修订
你this.config
总是在继承组件是可见的。不需要在SportTemplates
组件中再次注入appConfig
。
谢谢你的回复。我在我的问题中加了一点澄清。 –
@NikolaYankov更新回答问题 –
你可以这样做:
myService: MyService = this.injector.get(MyService);
constructor(private injector:Injector) {}
注射器是@角/核心
虽然它的工作,它看起来并不像真正的方式。更像服务定位器模式。尽管我不得不承认这种差异很微妙。 – XOR
你有没有发现用于构造器注入的最佳解决方案? – PaladiN
我在这里找到了我的问题的答案: https://*.com/questions/42461852/angular-2-inject-service-manually谢谢。 –