在 Angular 模板中渲染 Observable 对象属性

Mig*_*ura 2 angular angular-observable angular7

我有以下 Angular 7 组件:

export class PostComponent implements OnInit {

  post$: Observable<PostModel>;

  constructor(private postService: PostService) { }

  ngOnInit() {

    this.post$ = postService.getPostById(25);

  }

}
Run Code Online (Sandbox Code Playgroud)

在组件模板上,我使用了以下内容:

<p>Title: {{post$.title}}</p>
Run Code Online (Sandbox Code Playgroud)

标题显示为空,我认为是因为 post$ 是一个 Observable。

使用数组时,例如posts$: Observable<PostModel[]>我将 observable 传递给模板,并且使用ngFor.

但是在这种情况下我应该怎么做呢?

用数组观察

使用数组的 Observable 时,我在 HTML 模板中有以下内容:

<div *ngIf="(posts$ | async)?.length > 0; else loading">
  <ng-container *ngFor="let post of posts$ | async">
    {{post.title}}
  </ng-container>
</div>
<ng-template #loading>
  Loading ...
</ng-template>
Run Code Online (Sandbox Code Playgroud)

这允许我在加载时显示加载消息。

Nik*_*kos 6

您必须将异步管道用作:

<p>Title: {{(post$ | async).title}}</p>
Run Code Online (Sandbox Code Playgroud)