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

查看:67
本文介绍了如何使用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<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)
        };
      })
    );
  }

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

 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);
    }

任何帮助将不胜感激.

解决方案

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

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

但是,由于您没有任何初始状态,因此应使用ReplaySubject而不是BehaviorSubject.而且由于数据返回是一回事,所以我将使用一个主题.

首先,我将声明一个接口,以使讨论数据类型更加容易.

earthquake-data.ts

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

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

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)
        });
      })
    );
  }
 

因此,现在,所有想要接收数据的组件都将订阅一种方法:

 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();
}
 

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

 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天全站免登陆