【问题标题】:Refresh one Component on click event of Another Component in Angular在Angular中另一个组件的单击事件上刷新一个组件
【发布时间】:2021-02-06 10:08:00
【问题描述】:

我在 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.

我在第三个组件中使用了两个组件,如下所示:

组件 3

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

我想在单击 Component1 中的按钮时刷新 Component2 数据。如何做到这一点?

【问题讨论】:

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

标签: angular typescript components


【解决方案1】:

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

您可以让 component1 中的按钮触发服务上的功能

假设组件 2 的网格中的数据也来自同一个服务,一旦数据发生变化,组件会自动刷新

这个答案有一个很好的例子:https://stackoverflow.com/a/61806447/4604645

【讨论】:

    【解决方案2】:

    您可以使用rxjs BehaviorSubject

    首先创建一个名为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);
        }
    }
    

    component1.ts inject service 和按钮上单击只需在notifyOther notifyOther function 中发送{refresh: true} object ,稍后将由component2 订阅。

    refreshGridInAnotherComponent(){
        this.dataService.notifyOther({refresh: true});
    }
    

    在您的component2.ts 中,您可以像这样从component's ngOnInit 上的可观察对象中subscribe

    copmonet2.ts

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

    【讨论】:

      猜你喜欢
      • 2017-03-10
      • 1970-01-01
      • 2017-12-02
      • 2019-02-24
      • 2018-12-02
      • 1970-01-01
      • 2020-07-18
      • 2020-07-11
      • 1970-01-01
      相关资源
      最近更新 更多