我试图从服务类调用组件方法,但收到类似“错误类型错误:无法读取未定义的属性“测试””的错误。但我遇到了类似的问题,但主要是解释组件到组件的调用,所以我没有正确理解。
示例: 测试组件.ts
@Component({
selector:'component'
})
export class Testcomponent{
test(){
console.log('test method');
}
}
@Injectable()
export class Testservice {
private testcomp: Testcomponent;
// service method
dummy(){
//trying to call component method
testcomp.test();
}
}
这就是我的调用方式,我不确定这是否是正确的方法,所以任何人都可以让我了解如何从服务调用组件方法。
我在堆栈中浏览了这个引用,但没有得到到底在做什么 How to call component method from service? (angular2)
最佳答案
尝试以下代码。引用请访问https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service
export class Testcomponent {
constructor(private testService: Tesetservice) {
this.testService.testComponent$.subscribe(res => {
this.test()
})
}
test() {
console.log('test method');
}
}
export class Testservice {
private testComponentSource = new Subject<boolean>();
// Observable string streams
testComponent$ = this.testComponentSource.asObservable();
// service method
dummy() {
//trying to call component method
this.testComponentSource.next(null);
}
}
关于angular - 如何从服务类调用组件方法 - Angular,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57668759/