Angular 在对象中使用服务或在构造函数中使用服务创建对象
我有一个表单设置:Angular 在对象中使用服务或在构造函数中使用服务创建对象,angular,Angular,我有一个表单设置: export const fields = [ { key: 'key', options: myService.get() // how can I call service method here? } ] 我想知道这样的事情: class MyFields { fields = [ { key: 'key', options: this.myService.get() } ] cons
export const fields = [
{
key: 'key',
options: myService.get() // how can I call service method here?
}
]
我想知道这样的事情:
class MyFields {
fields = [
{
key: 'key',
options: this.myService.get()
}
]
constructor(private myService: MyService) {}
}
@Component...
export class MyComponent {
constructor() {
const fields = new MyFields().fields;
}
}
但我必须将服务传递给:
new MyFields().fields;
构造器
您知道怎么做吗?因为MyFields已经在其构造函数中接受服务,现在您只需要调用
new MyFields(passedService).fields;
确实如此。您也可以从ngOnInit调用服务函数
但我不想在这里通过这项服务。MyComponent是一个子类,我以前必须调用super。所以我不能在MyComponent构造函数中使用“this”来传递这个。passedServiceWhy不能?您可以拥有一个子类,该子类调用super并具有自己的注入服务。底线是——如果你想在MyFields类中使用一个服务,你必须要么把它注入到它里面,就像你在它的构造函数中已经做的那样,要么把这个服务变成一个全局变量,这样你就可以不用注入就可以使用它。
class MyFields {
fields = [
{
key: 'key',
options:''
}
]
constructor(private myService: MyService) {
const fields = new MyFields(this.myService).fields;
}
// Another way
ngOnInit(){
this.fields[0].options = this.myService.get();
}