[英]Angular: call function from other component
I'm trying to make two angular components and I want to call a function from the first component in the second component. 我正在尝试制作两个角度组件,并且想从第二个组件的第一个组件调用一个函数。 When I try this I get following error message:
Cannot red property 'functionName' of undefined
. 当我尝试此操作时,出现以下错误消息:
Cannot red property 'functionName' of undefined
。 How can this be solved? 如何解决呢?
Here a link of an example: https://stackblitz.com/edit/angular-rre4gb 这里是示例的链接: https : //stackblitz.com/edit/angular-rre4gb
That's because the component you want to call its function, is not instantiated. 这是因为您要调用其功能的组件未实例化。
for component communication you can use a service
instead: 对于组件通信,可以改为使用
service
:
@Injectable()
export class MyService {
myCustomFunction(){
}
}
in your component: 在您的组件中:
@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();
}
}
As others have stated, I would prefer a shared service with a Subject
among these components. 正如其他人所说,在这些组件中,我希望与
Subject
共享服务。
service : 服务内容 :
@Injectable()
export class SharedService {
mySubject = new Subject();
}
WorldComponent (subscriber): WorldComponent (订阅者):
export class WorldComponent {
constructor(private sharedService: SharedService){
this.sharedService.mySubject.subscribe((data)=>{
this.worldFunction();
})
}
HelloComponent (publisher): HelloComponent (发布者):
public helloFunction() {
alert('Hello');
this.sharedService.mySubject.next(true);
}
You can find the updated example here: https://stackblitz.com/edit/angular-rnvmkq?file=app%2Fworld.component.ts 您可以在这里找到更新的示例: https : //stackblitz.com/edit/angular-rnvmkq?file=app%2Fworld.component.ts
The best way to share information between multiple components is generally through a service. 在多个组件之间共享信息的最佳方法通常是通过服务。
Create a separate file: file.service.ts 创建一个单独的文件:file.service.ts
Provide the service in the app.module.ts file 在app.module.ts文件中提供服务
Inject the service into each component. 将服务注入每个组件。 Then you'll have access to the variables in both components
然后,您将可以访问两个组件中的变量
See this: https://angular.io/tutorial/toh-pt4 看到这个: https : //angular.io/tutorial/toh-pt4
错误的原因是,hello组件未导入,但您不应在其他组件之间调用服务,而应从其他组件调用组件,就像已经提出的其他答案一样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.