【问题标题】:async pipe does not work on rxjs from observable异步管道不适用于可观察的 rxjs
【发布时间】:2020-07-27 23:19:52
【问题描述】:

我想对 from 返回的简单可观察对象使用异步管道:

在component.ts中

 myData$ = from([
    { name: "Los Angeles", population: "3.9 million" },
    { name: "New York", population: "8,4 million" },
    { name: "Chicago", population: "2.7 million" },
  ]);

在component.html中

<ul>
    <li *ngFor="let city of myData$ | async">
      {{city}}
    </li>
  </ul>

我得到的错误:

错误错误:找不到“芝加哥”类型的不同支持对象“[object Object]”。 NgFor 只支持绑定到 Arrays 等 Iterables。

【问题讨论】:

  • 请在 RxJs 中使用 of 运算符而不是 from 运算符。
  • 这能回答你的问题吗? 'of' vs 'from' operator

标签: angular rxjs angular-pipe angular-observable


【解决方案1】:

如果您使用from 运算符,您将一个接一个地接收每个数组项,而不是整个数组。因此,将from 运算符更改为of,这样您将接收到整个数组并对其进行循环。

myData$ = of([
    { name: "Los Angeles", population: "3.9 million" },
    { name: "New York", population: "8,4 million" },
    { name: "Chicago", population: "2.7 million" },
  ]);

<ul>
  <li *ngFor="let city of myData$ | async">
    {{ city | json }}
  </li>
</ul>

【讨论】:

    【解决方案2】:

    查看myData$ 的类型。它将是Observable&lt;{ name:string, population }&gt;,但是 ngFor 不会那样工作,它需要数组,因此您应该将 Observable&lt;{ name:string, population }[]&gt; 的类型传递给异步管道并且 ngFor 将工作。

    这就是为什么你需要使用of() 而不是from()

    【讨论】:

      猜你喜欢
      • 2020-09-26
      • 1970-01-01
      • 1970-01-01
      • 2017-01-10
      • 1970-01-01
      • 2016-08-14
      • 2019-09-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多