【问题标题】:Subscription is not assignable to NgIterable订阅不可分配给 NgIterable
【发布时间】:2023-01-09 09:23:54
【问题描述】:

目标:我想在前端显示用户数据

我有一个具有以下结构的用户模型IPerson:

export interface IPerson {
  name: string;
  email: string;
  passwort: string;
}

在 Auth 服务中,我创建了一个这种类型的可观察对象,一旦我 next() 进入其中,它就应该保存个人资料信息

public loggedInUserData = new ReplaySubject<IPerson>();

在配置文件组件中,我想获取此可观察对象的最新有效负载并将其存储

public profiles$ = this.authService.loggedInUserData.subscribe((res) => {
  return res;
});

最后,我想以 HTML 格式显示收到的用户数据

<tr *ngFor="let profile of profiles$">
  <td>{{ profile.name }}</td>
  <td>{{ profile.email }}</td>
  <td>{{ profile.passwort }}</td>
</tr>

问题:我收到以下错误:

类型“订阅”不可分配给类型“NgIterable |空 |不明确的'

【问题讨论】:

  • 不要订阅您的组件。而是在模板中使用 async 管道,它将起作用:*ngFor="let profile of profiles$ | async"
  • 这有效,但它无助于我理解为什么我的解决方案不起作用。从技术上讲,异步管道也只是订阅可观察的
  • 异步管道将发出的值传递给您的 ngFor。你这样做的方式是传递一个 Subscription 对象。

标签: angular typescript rxjs


【解决方案1】:

认为您需要 scan rxjs 运算符将 IPerson 对象累积为 Observable&lt;IPerson[]&gt;。

import { scan } from 'rxjs/operators';

public profiles$: Observable<IPerson[]> = this.authService.loggedInUserData
  .asObservable()
  .pipe(scan((acc, curr) => [...acc, curr], []));

并使用 async 管道订阅可观察对象。

<tr *ngFor="let profile of profiles$ | async">
  <td>{{ profile.name }}</td>
  <td>{{ profile.email }}</td>
  <td>{{ profile.passwort }}</td>
</tr>

Sample StackBlitz Demo

【讨论】:

    猜你喜欢
    • 2019-08-01
    • 1970-01-01
    • 2016-11-12
    • 2021-04-16
    • 2022-09-24
    • 1970-01-01
    • 2021-08-15
    • 1970-01-01
    • 2017-05-06
    相关资源
    最近更新 更多