首页 > 解决方案 > rxjs 地图创建重复

问题描述

在这张地图中,我试图更新索引上的数组。这似乎是在创建一个副本。想法?

const updateAirport$ = this.updateAirportSubject$
    .pipe(
        filter(airport => !!airport),
        switchMap(airport => this.airportService.updateAirport(airport)),
        tap(airport => {
            this.snackBar.open(`${airport.name} updated`, null, snackBarConfig);
            this.saveStatus = 2;
        }),
        map(airport => {
            const index = this.airports.findIndex(item => item.id === airport.id);
            this.airports = [...this.airports, this.airports[index] = airport];
            return this.airports;
        }),
        tap(() => this.saveStatus = 0),
        shareReplay()
    );

接着:

this.airports$ = airports$.pipe(
    merge(newAirport$, updateAirport$, uploadCSV$)
);

标签: angularrxjs

解决方案


这是一个难以诊断的问题,因为我没有完整的解决方案,以下分析将基于我的一些假设,如果有错误请纠正我。

您的地图逻辑正在此处创建单个索引的不可变副本。

this.airports = [...this.airports, this.airports[index] = airport];

然后将其输出合并到此处。

merge(newAirport$, updateAirport$, uploadCSV$)

如果逻辑this.updateAirportSubject$基于您的副本,newAirport$则将不可变副本放回自身...如果是这种情况,请newAirport$在合并之前删除原始索引或修改原始索引而不创建不可变副本。

修订

仔细观察,我相信这个逻辑是你问题的原因,我不太清楚你在这条线上试图完成什么。

  • 您正在创建索引的不可变副本this.airports并在末尾附加索引的副本。

    this.airports = [...this.airports, this.airports[index] = airport];
    

您已经使用这里获得了索引airport.id

  const index = this.airports.findIndex(item => item.id === airport.id);

然后使用索引在机场进行布尔匹配,以确保索引与发出的值匹配,然后附加到this.airports.

this.airports[index] = airport

例子

下面的逻辑

array = [1,2,3,4,5,6,7,8,9]
  index;

  ngOnInit(){
    this.index = this.array.indexOf(4);
    this.array = [...this.array, this.array[this.index] = 4];
    console.log(this.array);
  }

导致此输出。

1,2,3,4,5,6,7,8,9,4

推荐阅读