本文介绍了在Observable of Observables(Angular)上的ngFor中使用异步管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样定义的变量:myVar: Observable<Observable<MyObject>[]>.

I have variable defined like this: myVar: Observable<Observable<MyObject>[]>.

我正在使用Angular4功能枚举异步管道

I am using Angular4 feature to enumerate with async pipe

*ngFor="let obsMyObject of (myVar | async)"

现在我有MyObject的Observable,但是我只需要MyObject.我可以这样写:

now I have Observable of MyObject, but I need just MyObject. I could write something like that:

<div *ngFor="let obsMyObject of (myVar | async)">
    <div *ngIf="let obsMyObject | async; let MyObject"></div>
</div>

但是我不能在内部div中执行此操作,因为我正在设置flex order(对内部div没有任何影响)属性,所以我需要这样的东西:

but I can not do this in inner div, because I am setting flex order (which doesn't have any effect on inner div) property so I need something like this:

<div *ngFor="let obsMyObject of (myVar | async); let MyObject = (obsMyObject | async)"
    [style.order]="MyObject.order">
</div>

我只是有一个想法,我尝试过:

I just had one idea how to do this, and I tried this:

<div *ngFor="let obsMyObject of (myVar | async); let MyObject = obsMyObject)">
    {{MyObject}}
</div>

但是MyObject是未定义的,因此let MyObject = (obsMyObject | async)将无法工作.

but MyObject is undefined, so there is no way let MyObject = (obsMyObject | async) would work.

推荐答案

我认为您想使用ng-containerngIf订阅并创建对可观察对象的引用.然后在ng-container内部,您可以引用此新变量,就好像它是一个普通对象一样.

I think you want to use an ng-container and an ngIf to subscribe and create reference to the observable. Then from within the ng-container you can reference this new variable as if it was a plain object.

<ng-container *ngIf="myVar$| async as myVar">
   <div *ngFor="let obsMyObject of myVar">
    {{obsMyObject }}
   </div>
</ng-container>

myVar和对象的使用确实令人困惑.这是一个更好的例子:

The use of myVar and object is really confusing. Here's a better example:

组件中的属性声明为:

users$: Observable<User[]>

和模板:

<ng-container *ngIf="users$ | async as users">
   <div *ngFor="let user of users">
     {{ user.name }}
   </div>
</ng-container>

这篇关于在Observable of Observables(Angular)上的ngFor中使用异步管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 01:40