Sar*_*a N 4 events components event-handling listener angular
在 Angular2 中,假设我有 component1(将其用作左侧面板导航器)和 component2 。这两个组件彼此不相关(兄弟姐妹,父子关系,......)。如何从 component2 调用 component1 中的函数?我不能在这里使用事件绑定。
您可以使用 angular BehaviorSubject 与非相关组件进行通信。
服务文件
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);
}
}
Run Code Online (Sandbox Code Playgroud)
第一个组件
constructor(private _data: commonService) { }
shareData() {
this._data.updateMessage('pass this data');
}
Run Code Online (Sandbox Code Playgroud)
第二个组件
constructor(private _data: commonService) { }
ngOnInit() {
this._data.currentData.subscribe(currentData => this.invokeMyMethode())
}
Run Code Online (Sandbox Code Playgroud)
使用上述方法,您可以使用非相关组件轻松调用方法/共享数据。
共享服务是非相关组件之间通信的常用方式。您的组件需要使用该服务的单个实例,因此请确保它是在根级别提供的。
共享服务:
@Injectable()
export class SharedService {
componentOneFn: Function;
constructor() { }
}
Run Code Online (Sandbox Code Playgroud)
组件一:
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!`);
}
}
Run Code Online (Sandbox Code Playgroud)
第二部分:
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!
}
}
}
Run Code Online (Sandbox Code Playgroud)
这篇文章可能也有帮助:Angular 2 Interaction between Components using a service
| 归档时间: |
|
| 查看次数: |
21815 次 |
| 最近记录: |