交换可观察数组中的元素

swap element in an observable array

我正在尝试交换可观察数组中的两个项目。我知道如何在普通数组中进行操作。我试过同样的方法,但它没有改变值。

My Stackblitz code

这是我试过的,

swapObservableArray() {
    let index;

    // get the index
    this.productss$
      .pipe(findIndex((a) => a.id === 5))
      .subscribe((a) => (index = a));

    // swap the items
    [this.productss$[2], this.productss$[index]] = [
      this.productss$[index],
      this.productss$[2],
    ];
    this.productss$.subscribe((a) => console.log(a));
  }

这就是你想要达到的目标吗?请注意,我还修改了 productss$ 的初始化方式。

Stackblitz code


import { Component } from '@angular/core';
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';

interface fruits {
  name: string;
  id: number;
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  productss$: Observable<fruits[]> = of([
    { name: 'orange', id: 1 },
    { name: 'grapes', id: 2 },
    { name: 'mango', id: 3 },
    { name: 'kiwi', id: 4 },
    { name: 'strawberry', id: 5 },
    { name: 'blueberry', id: 6 },
  ]);
  normalProduct: fruits[] = [
    { name: 'orange', id: 1 },
    { name: 'grapes', id: 2 },
    { name: 'mango', id: 3 },
    { name: 'kiwi', id: 4 },
    { name: 'strawberry', id: 5 },
    { name: 'blueberry', id: 6 },
  ];

  constructor() {}
  ngOnInit() {
    this.swapNormalArray(); // works
    this.swapObservableArray(); // doesn't work
  }

  swapNormalArray() {
    // find the index
    const index = this.normalProduct.findIndex((a) => a.id === 5);
    // swap the item
    [this.normalProduct[2], this.normalProduct[index]] = [
      this.normalProduct[index],
      this.normalProduct[2],
    ];
    console.log('Normal', this.normalProduct);
  }
  swapObservableArray() {
    this.productss$
      .pipe(
        map((value: fruits[]) => {
          const idx = value.findIndex((a) => a.id === 5);
          [value[2], value[idx]] = [value[idx], value[2]];
          return value;
        })
      )
      .subscribe((a) => console.log('Observable Array', a));
  }

  ngOnDestroy() {}
}