简体   繁体   English

angular - 如何编写正确的 ngIf 条件 - 数组长度是否大于 1

[英]angular - how to write correct ngIf condition - is array length is bigger then 1

I have angular code and I put condition like this:我有 angular 代码,我输入了这样的条件:

<li *ngIf="carProfiles$.length > 1">

and this works, but this .length is red in my editor and it writes这行得通,但是这个.length在我的编辑器中是红色的,它写道

unresolved variable length

I'm worried about this because no matter this code works it seems I did something wrong.我对此很担心,因为无论这段代码是否有效,似乎我做错了什么。 In the ts file:在 ts 文件中:

readonly carProfiles$: Observable<Profile[]>;

and inside constructor:和内部构造函数:

this.carProfiles$ = this.allProfiles$.pipe(map((profiles) => profiles.filter((p) => ProfileHelper.isCar(p))));

Any help?有什么帮助吗? DO I need to worry about why text.length is red and did I write condition in the correct way?我是否需要担心为什么 text.length 是红色的,我是否以正确的方式编写了条件?

You are not trying to check an array length.您不是在尝试检查数组长度。 You are trying to check the observable's length (and is not correct) which emits an array.您正在尝试检查发出数组的可观察对象的长度(并且不正确)。 Instead you can first extract the emitting array inside observable by using async pipe, then check for length.相反,您可以先使用async pipe 提取可观察对象内部的发射数组,然后检查长度。 This async pipe is subscribing to this Observable in the backgorund and unsubscribing from it.这个async pipe 在后台订阅这个Observable并取消订阅它。

<li *ngIf="(carProfiles$| async)?.length > 0">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM