Shr*_*r S 1 components typescript angular
我在 Angular-9 应用程序中有 3 个组件,如下所示:
组件1
<div>
// I have a button here with Click Event.
</div>
Run Code Online (Sandbox Code Playgroud)
组件2
<div>
// I have a Grid here.
</div>
In a class file I'm getting Data and Binding Grid using ngOnInit() method.
Run Code Online (Sandbox Code Playgroud)
我在第三个组件中使用这两个组件,如下所示:
组件 3
<div id='third-component'>
<component-one></component-one>
<component-two></component-two>
</div>
Run Code Online (Sandbox Code Playgroud)
我想通过单击Component1中的按钮刷新Component2数据。这个怎么做?
您可以使用rxjs BehaviorSubject。
首先创建一个名为data.service.tsand 的服务,在其中创建一个observableof 类型BehaviorSubject和一个将值推入其中的函数BehaviorSubject。
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
public notify = new BehaviorSubject<any>('');
notifyObservable$ = this.notify.asObservable();
public notifyOther(data: any) {
if (data) {
this.notify.next(data);
}
}
Run Code Online (Sandbox Code Playgroud)
然后在component1.ts inject该service按钮上单击“发送” {refresh: true} object,稍后notifyOther function将订阅该按钮component2。
refreshGridInAnotherComponent(){
this.dataService.notifyOther({refresh: true});
}
Run Code Online (Sandbox Code Playgroud)
在你身上component2.ts你可以subscribe从component's ngOnInit这样的可观察到的
copmonet2.ts
ngOnInit(){
this.dataService.notifyObservable$.subscribe(res => {
if(res.refresh){
// get your grid data again. Grid will refresh automatically
this.dataService.getData();
}
})
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6620 次 |
| 最近记录: |