我有问题。我在组件A中有一个方法,我想从构造函数中在组件B中调用此方法。示例:
export class A {
methodA() {
do something;
}
}
export class B {
constructor(private a:A){}
methodB() {
this.a.methodA();
}
}
我有这个问题:Can't resolve all parameters for CategoryComponent
答案 0 :(得分:0)
Component Interaction角度的最佳实践取决于这两个分量之间的关系。
简而言之:
答案 1 :(得分:-1)
我认为您需要将A
组件添加到B
组件的提供程序中,因此您的class B
应该看起来像这样
import {A} from 'path/to/A.component';
// other imports
@Component({
selector: 'b-component',
templateUrl: './b.component.html',
providers: [A] // this is what you are missing
})
export class B implements OnInit {
constructor(private a: A) {
}
// move function out of constructor
ngOnInit() {
this.methodB();
}
methodB() {
this.a.methodA();
}
}
此外,向构造函数添加任何逻辑也不是一个好习惯。您确实应该在ngOnInit
或ngAfterViewInit
中使用它。