Search code examples
angulartypescriptobservableclonengrx

Cloning data - ERROR Error: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'


I am trying to clone data from NGRX store so i can edit them.

Declarations

public stuff$: Observable<StuffModel> | undefined;
public editableStuff$: Observable<StuffModel> | undefined;

TS

ngOnInit() {
    this.editableStuff$ = Object.assign(
      {},
      (this.stuff$ = .........
          id === 'newStuff'
            ? of(this.newStuff)
            : this.store.pipe(
                ...............
                select((entities) => entities[id] ?? ({} as StuffModel))
              )
        )
      ))
    );
  }

HTML

<ng-container *ngIf="editableStuff$ | async as stuff">
...
<input
          matInput
          placeholder="Stuff"
          [(ngModel)]="stuff.stuffName"
        />

Problems is that i am getting error ERROR Error: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe' and dont know why. When i use <ng-container *ngIf="stuff$ | async as stuff"> it works but how can i make it work with editableStuff$? When i console log bot variables stuff$ and editabelStuff$ with JSON.stringify() they are same.


Solution

  • You are using Object.assign, that creates an object, so what you have now, is an object containing an observable. If you want to make a copy of an observable, a map should suffice, so something like this (simplified):

    this.editableStuff$ = this.stuff$.pipe(
      map(item => ({ ...item }))
    );
    

    Where we use the spread operator to copy the item.