在Angular2中,假设我有component1(用作左侧面板导航器)和component2。这两个组件彼此不相关(同级,父级和子级...) 。 如何从component2调用component1中的函数? 我不能在这里使用事件绑定。在另一个组件中调用一个组件的函数
2
A
回答
2
共享服务是非相关组件之间通用的通信方式。 您的组件需要use a single instance of the service,因此请确保它在根级别提供。
共享服务:
@Injectable()
export class SharedService {
componentOneFn: Function;
constructor() { }
}
组件之一:
export class ComponentOne {
name: string = 'Component one';
constructor(private sharedService: SharedService) {
this.sharedService.componentOneFn = this.sayHello;
}
sayHello(callerName: string): void {
console.log(`Hello from ${this.name}. ${callerName} just called me!`);
}
}
组件二:
export class ComponentTwo {
name: string = 'Component two';
constructor(private sharedService: SharedService) {
if(this.sharedService.componentOneFn) {
this.sharedService.componentOneFn(this.name);
// => Hello from Component one. Component two just called me!
}
}
}
此信息可能是有用的,以及:Angular 2 Interaction between components using a service
+0
这是否仍然工作10/24/2017?尝试完全按照指定,但从comp2调用时,comp1的名称出现未定义。 – overboard182
0
可以使用角行为主题与非相关组件进行通信。
服务文件
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class commonService {
private data = new BehaviorSubject('');
currentData = this.data.asObservable()
constructor() { }
updateMessage(item: any) {
this.data.next(item);
}
}
第一组分
constructor(private _data: commonService) { }
shareData() {
this._data.updateMessage('pass this data');
}
第二部分
constructor(private _data: commonService) { }
ngOnInit() {
this._data.currentData.subscribe(currentData => this.invokeMyMethode())
}
使用ABOV您可以使用非相关组件轻松调用方法/共享数据。
相关问题
- 1. 调用另一个组件中的一个组件的方法?
- 2. 从一个组件调用函数到另一个组件Angularjs 2
- 3. 在React中调用多个函数,一个内部和另一个组件外?
- 4. Angular2从另一个组件调用一个功能组件
- 5. ReactJS - 从另一个组件调用一个组件方法
- 6. 如何从ReactJS中的onClick函数调用另一个组件
- 7. 如何从reactJs中的另一个组件调用timeinterval函数?
- 8. 你如何在另一个组件中调用组件?
- 9. 从React中的另一个无关组件调用一个组件的功能
- 10. php从另一个文件中调用另一个函数的变量并将其传递给一个数组
- 11. 从自定义组件中调用另一个JSF组件
- 12. 反应调用另一个组件
- 13. 从另一个组件调用ref(?)
- 14. 如何在子组件中调用函数:a)另一个子组件b)父组件,反之亦然?
- 15. 从一个组件到另一个组件中的角4
- 16. 灰烬JS:从一个组件到另一个数据组件
- 17. 将数据从一个组件传递到另一个组件
- 18. 如何在ng-forward中将函数回调从一个组件传递到另一个组件
- 19. Angular2 - 在另一个组件
- 20. 在angularjs中调用另一个数组中的json数组
- 21. 聚合物JS从一个组件传递函数到另一个组件?
- 22. 从另一个JS文件中的另一个函数调用JavaScript函数
- 23. 在另一个函数中使用在一个函数中声明的数组
- 24. 从另一个函数调用另一个函数在这个
- 25. Vue.js在另一个组件的组件中使用变量
- 26. 从另一个文件调用函数
- 27. 从另一个文件调用函数
- 28. 数组的累积和,在另一个数组中的条件
- 29. 如何从另一个组件调用组件方法?
- 30. Angular 2:从另一个组件调用现有组件
你可能会使用一个[服务](https://angular.io/docs/ts/latest/tutorial/toh-pt4.html)来管理该连接。 – ryannjohnson
使用流量模式 - 服务是事件的调度程序,组件是订户。组件并不真正了解对方。这可能是有用的:http://stackoverflow.com/questions/42219858/how-can-i-maintain-the-state-of-dialog-box-with-progress-all-over-my-angular-2-a/42221273#42221273 – pixelbits
@ryannjohnson在component1中,我有内插{{total}},需要立即更新并显示在左侧面板中。如果我只是致电服务,我该如何更新这个变量? –