在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}},需要立即更新並顯示在左側面板中。如果我只是致電服務,我該如何更新這個變量? –