【问题标题】:swap element in an observable array交换可观察数组中的元素
【发布时间】:2022-01-23 05:59:17
【问题描述】:

我正在尝试交换可观察数组中的两个项目。我知道如何在普通数组中做到这一点。我尝试了同样的方法,但它并没有改变值。

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

【问题讨论】:

  • 你能解释一下你想换什么吗?你知道你的交换发生在 findIndex 之前吗?你知道 this.productss$[2] 只是未定义吗?

标签: angular rxjs observable rxjs-pipeable-operators rxjs-marbles


【解决方案1】:

这就是你试图达到的目标吗?请注意我还修改了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() {}
}


【讨论】:

  • 请分享stackblitz
  • 如果你还需要这个,我添加了链接。
  • 请为我的问题投票
猜你喜欢
  • 2018-11-26
  • 1970-01-01
  • 1970-01-01
  • 2014-01-28
  • 2012-06-30
  • 2022-11-08
  • 1970-01-01
  • 2019-06-04
  • 2020-02-08
相关资源
最近更新 更多