angular – 从另一个组件调用组件中的函数

前端之家收集整理的这篇文章主要介绍了angular – 从另一个组件调用组件中的函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在Angular2中,假设我有component1(使用它作为左面板导航器)和component2.这两个组件彼此不相关(兄弟,父和子,……).
如何从component2调用component1中的函数
我不能在这里使用事件绑定.
共享服务是非相关组件之间通信的常用方式.
您的组件需要 use a single instance of the service,因此请确保它在根级别提供.

共享服务:

  1. @Injectable()
  2. export class SharedService {
  3.  
  4. componentOneFn: Function;
  5.  
  6. constructor() { }
  7. }

第一部分:

  1. export class ComponentOne {
  2.  
  3. name: string = 'Component one';
  4.  
  5. constructor(private sharedService: SharedService) {
  6. this.sharedService.componentOneFn = this.sayHello;
  7. }
  8.  
  9. sayHello(callerName: string): void {
  10. console.log(`Hello from ${this.name}. ${callerName} just called me!`);
  11. }
  12. }

第二部分:

  1. export class ComponentTwo {
  2.  
  3. name: string = 'Component two';
  4.  
  5. constructor(private sharedService: SharedService) {
  6. if(this.sharedService.componentOneFn) {
  7. this.sharedService.componentOneFn(this.name);
  8. // => Hello from Component one. Component two just called me!
  9. }
  10. }
  11. }

这篇文章也许有帮助:Angular 2 Interaction between components using a service

猜你在找的Angularjs相关文章