[英]Angular: call function from other component
我正在尝试制作两个角度组件,并且想从第二个组件的第一个组件调用一个函数。 当我尝试此操作时,出现以下错误消息: Cannot red property 'functionName' of undefined
。 如何解决呢?
这里是示例的链接: https : //stackblitz.com/edit/angular-rre4gb
这是因为您要调用其功能的组件未实例化。
对于组件通信,可以改为使用service
:
@Injectable()
export class MyService {
myCustomFunction(){
}
}
在您的组件中:
@Component({
selector: 'my-component',
providers: [ MyService ]
})
export class MyComponent {
// inject your service to make it available
constructor(private service: MyService){}
doStuff(){
// call function which is located in your service
this.service.myCustomFunction();
}
}
正如其他人所说,在这些组件中,我希望与Subject
共享服务。
服务内容 :
@Injectable()
export class SharedService {
mySubject = new Subject();
}
WorldComponent (订阅者):
export class WorldComponent {
constructor(private sharedService: SharedService){
this.sharedService.mySubject.subscribe((data)=>{
this.worldFunction();
})
}
HelloComponent (发布者):
public helloFunction() {
alert('Hello');
this.sharedService.mySubject.next(true);
}
您可以在这里找到更新的示例: https : //stackblitz.com/edit/angular-rnvmkq?file=app%2Fworld.component.ts
在多个组件之间共享信息的最佳方法通常是通过服务。
创建一个单独的文件:file.service.ts
在app.module.ts文件中提供服务
将服务注入每个组件。 然后,您将可以访问两个组件中的变量
看到这个: https : //angular.io/tutorial/toh-pt4
错误的原因是,hello组件未导入,但您不应在其他组件之间调用服务,而应从其他组件调用组件,就像已经提出的其他答案一样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.