我试图从服务类调用组件方法,但收到类似“错误类型错误:无法读取未定义的属性“测试””的错误。但是我遇到了类似的问题,但主要解释了组件到组件的调用,所以我没有正确理解。
例子:
测试组件.ts
@Component({
selector:'component'
})
export class Testcomponent{
test(){
console.log('test method');
}
}
Testservice.ts
@Injectable()
export class Testservice {
private testcomp: Testcomponent;
// service method
dummy(){
//trying to call component method
testcomp.test();
}
}
这就是我的调用方式,我不确定这是否是正确的方法,所以任何人都可以让我了解如何从服务调用组件方法。
我在堆栈中浏览了这个参考但不明白到底在做什么如何从服务中调用组件方法? (角度2) https://stackoverflow.com/questions/40788458/how-to-call-component-method-from-service-angular2
尝试以下代码。供参考访问https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service 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);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)