如何使用 BehaviourSubjects 在 Angular 中的组件之间共享来自 API 调用的数据? [英] How to use BehaviourSubjects to share data from API call between components in Angular?

查看:15
本文介绍了如何使用 BehaviourSubjects 在 Angular 中的组件之间共享来自 API 调用的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在构建一个 Angular 应用程序,我在其中向 api 发出请求,并将响应映射到两个不同的数组.我可以在我的 app.components.ts 中使用这些数据,但我会根据我的需要制作新的组件.我如何在组件之间共享数据以确保组件始终拥有最新数据,因为我还需要定期调用 API.

我在 SO 和一些 youtube 视频上看到了一些答案,但我只是不完全理解.

我的服务代码是

 url = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson';private _earthquakePropertiesSource = new BehaviorSubject>([]);private _earthquakeGeometrySource = new BehaviorSubject>([]);构造函数(私有只读 httpClient:HttpClient){}public getEarthquakeData(): Observable<{ properties: [], geometries: []}>{返回 this.httpClient.get(this.url).pipe(//这将在响应返回时运行地图((响应:任何)=> {返回 {属性: response.features.map(x => x.properties),几何: response.features.map(x => x.geometry)};}));}

它在我的 app.component.ts 中使用如下:

 属性:Array;几何图形:数组<任何>;构造函数(私有只读地震服务:EarthquakeService){}ngOnInit() {this.earthquakeService.getEarthquakeData().subscribe(data => {this.properties = data.properties;this.geometries = data.geometries;this.generateMapData();});}生成地图数据(){for (const g of this.geometries) {const tempData: 任何 = {纬度:g.coordinates[0],经度:g.coordinates[1],可拖动:假,};this.mapData.push(tempData);}

任何帮助将不胜感激.

解决方案

这是一个描述如何使用纯 RxJS 完成的答案.另一种选择是使用 NgRx.

首先,您设置了两个主题.意图是所有组件都将订阅它们并在刷新时接收最新数据?

不过,您应该使用 ReplaySubject 而不是 BehaviorSubject,因为您没有任何初始状态.由于数据作为一件事返回,我将使用一个主题.

首先,我将声明一个接口,以便于讨论数据类型.

地震数据.ts

export interface EarthquakeData {//TODO: 为这些创建类型几何形状:任何[];属性:任何[];}

在您的服务中,您可以通过自己的方法公开数据来将检索和通知分开.

earthquake.service.ts

 url = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson';private _earthquakeData$ = new ReplaySubject(1);构造函数(私有只读 httpClient:HttpClient){}getEarthquakeData(): Observable{//这里返回主题//数据刷新时订阅者会收到通知返回 this._earthquakeData$.asObservable();}refreshEarthquakeData(): Observable{返回 this.httpClient.get(this.url).pipe(点击(响应 => {//通知所有订阅者有新数据this._earthquakeData$.next({几何: response.features.map(x => x.geometry),属性: response.features.map(x => x.properties)});}));}

所以现在,所有想要接收数据的组件都会订阅一个方法:

private destroy$ = new Subject();ngOnInit()this.earthquakeService.getEarthquakeData().pipe(//现在取消订阅主题很重要takeUntil(this.destroyed$)). 订阅(数据 => {控制台日志(数据);//最新数据});}ngOnDestroy() {this.destroyed$.next();this.destroyed$.complete();}

而且您可以随时随地刷新数据:

refreshData() {this.refreshing = true;this.earthquakeService.refreshEarthquakeData().subscribe(() => {this.refreshing = false;});}

演示:https://stackblitz.com/edit/angular-uv7j33>

I am currently building an Angular application where I make a request to an api, and I map the repsonse to two different arrays. I can use this data in my app.components.ts but I will make new components for what I need. How can I share the data between components to ensure that the components always have the latest data because I will also need to periodically call the API.

I've seen some answers on SO and some youtube videos but I'm just not fully understanding it.

The code of my service is

 url = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson'; 
  private _earthquakePropertiesSource = new BehaviorSubject<Array<any>>([]);
  private _earthquakeGeometrySource = new BehaviorSubject<Array<any>>([]);


  constructor(private readonly httpClient: HttpClient) {

  }


  public getEarthquakeData(): Observable<{ properties: [], geometries: []}> {
    return this.httpClient.get<any>(this.url).pipe(
      // this will run when the response comes back
      map((response: any) => {
        return {
          properties: response.features.map(x => x.properties),
          geometries: response.features.map(x => x.geometry)
        };
      })
    );
  }

It is being used in my app.component.ts as follows:

 properties: Array<any>;
 geometries: Array<any>;

constructor(private readonly earthquakeService: EarthquakeService) {
  }

  ngOnInit() {
    this.earthquakeService.getEarthquakeData().subscribe(data => {
      this.properties = data.properties;
      this.geometries = data.geometries;
      this.generateMapData();
    });
  }

  generateMapData() {
    for (const g of this.geometries) {
      const tempData: any = {
        latitude: g.coordinates[0],
        longitude: g.coordinates[1],
        draggable: false,
      };
      this.mapData.push(tempData);
    }

Any help would be greatly appreciated.

解决方案

This is an answer describing how it can be done using pure RxJS. Another alternative is to use NgRx.

Firstly, you have set up two subjects. The intention being that all components will subscribe to them and receive the latest data when it is refreshed?

You should use ReplaySubject instead of BehaviorSubject though, since you don't have any initial state. And since the data comes back as one thing, I would use one subject.

Firstly, I am going to declare an interface to make it easier to talk about the data types.

earthquake-data.ts

export interface EarthquakeData {
  // TODO: create types for these
  geometries: any[]; 
  properties: any[];
}

In your service, you can separate the retrieval and the notifications by exposing the data via your own methods.

earthquake.service.ts

  url = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson'; 

  private _earthquakeData$ = new ReplaySubject<EarthquakeData>(1);

  constructor(private readonly httpClient: HttpClient) {}

  getEarthquakeData(): Observable<EarthquakeData> {
    // return the subject here
    // subscribers will will notified when the data is refreshed
    return this._earthquakeData$.asObservable(); 
  }

  refreshEarthquakeData(): Observable<void> {
    return this.httpClient.get<any>(this.url).pipe(
      tap(response => {
        // notify all subscribers of new data
        this._earthquakeData$.next({
          geometries: response.features.map(x => x.geometry),
          properties: response.features.map(x => x.properties)
        });
      })
    );
  }

So now, all components that want to receive data will subscribe to one method:

private destroyed$ = new Subject();

ngOnInit()
  this.earthquakeService.getEarthquakeData().pipe(
    // it is now important to unsubscribe from the subject
    takeUntil(this.destroyed$)
  ).subscribe(data => {
    console.log(data); // the latest data
  });
}

ngOnDestroy() {
  this.destroyed$.next();
  this.destroyed$.complete();
}

And you can refresh the data wherever you want to:

refreshData() {
  this.refreshing = true;
  this.earthquakeService.refreshEarthquakeData().subscribe(() => {
    this.refreshing = false;
  });
}

DEMO: https://stackblitz.com/edit/angular-uv7j33

这篇关于如何使用 BehaviourSubjects 在 Angular 中的组件之间共享来自 API 调用的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆