在Angular中,在构造函数中调用子方法是一种不推荐的做法。通常,在构造函数中只应该执行一些基本的初始化操作,而将具体的业务逻辑放在其他方法中执行。
如果你需要在Angular服务中调用子方法,可以考虑以下解决方法:
@Injectable()
export class MyService {
private childMethod: () => void;
constructor() {
this.childMethod = this.myChildMethod.bind(this);
}
myChildMethod() {
// 子方法的实现
}
myParentMethod() {
// 在父方法中调用子方法
this.childMethod();
}
}
@Injectable()
export class MyService {
constructor() {
this.myChildMethod = this.myChildMethod.bind(this);
}
myChildMethod() {
// 子方法的实现
}
myParentMethod() {
// 在父方法中调用子方法
this.myChildMethod();
}
}
请注意,这些解决方法都遵循了良好的Angular编程实践,将具体的业务逻辑从构造函数中分离出来,以提高代码的可维护性和可测试性。