【问题标题】:Cloning data - ERROR Error: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'克隆数据 - 错误错误:InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'
【发布时间】:2021-07-04 15:57:34
【问题描述】:

我正在尝试从 NGRX 存储中克隆数据,以便编辑它们。

声明

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"
        />

问题是我收到错误ERROR Error: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe' 并且不知道为什么。当我使用&lt;ng-container *ngIf="stuff$ | async as stuff"&gt; 时,它可以工作,但我怎样才能使它与editableStuff$ 一起工作?当我使用JSON.stringify() 控制台记录机器人变量stuff$editabelStuff$ 时,它们是相同的。

【问题讨论】:

  • 你正在使用Object.assign,所以我不认为你为什么期望它是一个可观察的? Object assign 创建一个对象,而不是 observable。

标签: angular typescript observable clone ngrx


【解决方案1】:

您正在使用Object.assign,它创建了一个对象,所以您现在拥有的是一个包含可观察对象的对象。如果你想复制一个 observable,map 就足够了,所以像这样(简化):

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

我们在哪里使用扩展运算符来复制项目。

【讨论】:

  • 如果你有时间,我只有一个问题。如果我使用 this.editableStuff = JSON.parse(JSON.stringify(this.stuff$)); 但 editableStuff 是不可观察的,并且我从 html 中删除 async 它将不起作用并且只给我空字段你知道为什么吗?
  • 但是this.stuff$ 是可以观察到的吗?通过这样做,您不会获得可观察的价值。您需要以某种方式订阅 observable... 使用 subscribeasync 管道。
  • 澄清一下,您现在在评论中提到的操作是字符串化和解析 订阅,而不是可观察值。
猜你喜欢
  • 1970-01-01
  • 2020-10-28
  • 2018-05-23
  • 1970-01-01
  • 2018-06-22
  • 1970-01-01
  • 2021-01-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多