要在父类中添加一个服务,并使其在所有子类中起作用,可以按照以下步骤操作:
首先,在父类中创建一个服务,例如ParentService:
import { Injectable } from '@angular/core';
@Injectable()
export class ParentService {
// 服务的逻辑代码
}
然后,在子类中导入父类的服务,并在构造函数中注入:
import { Component } from '@angular/core';
import { ParentService } from 'path/to/parent.service';
@Component({
selector: 'app-child',
template: `
`,
})
export class ChildComponent {
constructor(private parentService: ParentService) {
// 子类的逻辑代码
}
}
最后,在父类中将ParentService提供给子类的组件:
import { Component } from '@angular/core';
import { ParentService } from 'path/to/parent.service';
@Component({
selector: 'app-parent',
template: `
`,
providers: [ParentService] // 将ParentService提供给子类的组件
})
export class ParentComponent {
// 父类的逻辑代码
}
通过这样的方式,父类中的ParentService将在所有子类中起作用。