对整个块使用异步管道和可观察的 [英] Use async pipe and observable for entire block

查看:81
本文介绍了对整个块使用异步管道和可观察的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Observable,它从API返回一个大对象.我需要在模板中显示这些值.

I have an Observable, which returns a large object from an API. I need to display these values in my template.

对于以数组形式返回的其他数据,我可以使用:

For other data returned as an array, I can use:

<div *ngFor="let value of values | async">
  <p>{{ value.prop }}</p>
</div>

我不需要等待*ngFor中的异步完成,因为它在父元素中已经有一个异步管道.

I don't need to wait for the async to complete within the *ngFor, as it's already got an async pipe in the parent element.

对于我的对象,我正在寻找类似的东西.此刻,我正在做类似的事情:

With my object, I'm looking for something similar. At the moment, I'm doing something like:

<h2>{{ (obj | async)?.title }}</h2>
<p>{{ (obj | async)?.prop.prop2 }}</p>
<p>{{ (obj | async)?.another.prop }}</p>

这显然会留下很多重复的代码.是否存在这样的东西?

This obviously leaves a lot of duplicate code. Does something like this exist?

<div *using="obj | async">
  <!-- obj has resolved, can access obj.prop -->
</div>

推荐答案

使用'as'语法.

还请注意,每个异步管道都会创建一个新的订阅,如果订阅使用http,则意味着多个http调用.如果要在带有异步管道的模板中多次使用相同的可观察值,请使用Rx share().

Also be aware that each async pipe creates a new subscription and if you subscription uses http - it means multiple http calls. Use Rx share() if you want to use the same observable multiple times in template with async pipe.

     @Component({
      selector: 'my-app',
      template: `
        <div>
          <div *ngIf="obj$ | async as obj; else empty">
         {{obj.x}}
         {{obj.y}}
         </div>
         <ng-template #empty>Empty. Wait 5 s...</ng-template>
        </div>
      `,
    })
    export class App {
      s = new Subject();
      obj$;
      constructor() {
        this.obj$ = this.s.asObservable();
        setTimeout(() => {
          this.s.next({x:12, y:100});
        }, 5000)
      }
    }

这篇关于对整个块使用异步管道和可观察的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆