Angular 在角度视图中另一个组件的单击事件时刷新一个组件

Angular 在角度视图中另一个组件的单击事件时刷新一个组件,angular,typescript,components,Angular,Typescript,Components,我在Angular-9应用中有3个组件,如下所示: 组件1 <div> // I have a button here with Click Event. </div> //我有一个点击事件按钮。 组件2 <div> // I have a Grid here. </div> In a class file I'm getting Data and Binding Grid using ngOnInit() method.

我在Angular-9应用中有3个组件,如下所示:

组件1

<div>
   // I have a button here with Click Event.
</div>

//我有一个点击事件按钮。
组件2

<div>
   // I have a Grid here. 
</div>

In a class file I'm getting Data and Binding Grid using ngOnInit() method.

//我这里有一个网格。
在类文件中,我使用ngOnInit()方法获取数据和绑定网格。
我在第三个组件中使用了两个组件,如下所示:

组件3

<div id='third-component'>
    <component-one></component-one>
    <component-two></component-two>
</div>


单击组件1中的按钮,我想刷新组件2数据。如何做到这一点?

在角度组件之间共享数据的答案是:使用角度服务

您可以使component1中的按钮触发服务上的一个函数

假设来自组件2的网格的数据也来自同一服务,一旦数据更改,组件将自动刷新


这个答案为您提供了一个很好的例子:

在角度组件之间共享数据的答案是:使用角度服务

您可以使component1中的按钮触发服务上的一个函数

假设来自组件2的网格的数据也来自同一服务,一旦数据更改,组件将自动刷新


这个答案为您提供了一个很好的例子:

您可以使用
rxjs 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);
    }
}
首先,只需创建一个名为
data.service.ts
的服务,并在其中创建一个类型为
BehaviorSubject
observable
,以及一个将值推入该
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);
    }
}
在您的
component2.ts
中,您可以
订阅
组件的ngOnInit上可观察到的内容,如下所示

copmonet2.ts

ngOnInit(){
    this.dataService.notifyObservable$.subscribe(res => {
          if(res.refresh){
              // get your grid data again. Grid will refresh automatically
              this.dataService.getData();
          }
    })
}

您可以使用
rxjs 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);
    }
}
首先,只需创建一个名为
data.service.ts
的服务,并在其中创建一个类型为
BehaviorSubject
observable
,以及一个将值推入该
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);
    }
}
在您的
component2.ts
中,您可以
订阅
组件的ngOnInit上可观察到的内容,如下所示

copmonet2.ts

ngOnInit(){
    this.dataService.notifyObservable$.subscribe(res => {
          if(res.refresh){
              // get your grid data again. Grid will refresh automatically
              this.dataService.getData();
          }
    })
}

您可以在服务上使用
rxjs Observable
。您可以在服务上使用
rxjs Observable