Estoy tratando de intercambiar dos elementos en la matriz observable. Sé cómo hacerlo en la matriz normal. Intenté de la misma manera pero no cambia el valor.
Esto es lo que probé,
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)); }¿Es eso lo que intentaste lograr? Por favor, preste atención que también modifiqué cómo se inicializa productss$ .
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() {} }