Angular ngIf: 标识符 'length' 未定义

Angular ngIf: Identifier 'length' is not defined

我的组件有 属性 transfers$,它是一个可观察对象,可以带有包含错误消息的数组或对象。 当 transfers$ 为 Transfer[] 时,我只能输入 [items]。但即使使用 condition

<app-checklist *ngIf="transfers?.length > 0" [items]="transfers"></app-checklist>

angular 继续警告:

标识符 'length' 未定义。 'Transfer[] | AppResponseError'不包含这样的成员

这是为什么?

谢谢

component.html

<ng-template #loadingTpl>loading</ng-template>

<ng-template #emptyList let-length="length">
    <p *ngIf="length === 0">Empty List</p>
</ng-template>

<ng-template #error let-title="title" let-message="message" let-code="code">
    <div *ngIf="code">
        Error: {{code}} , {{title}} , {{message}}
    </div>
</ng-template>

<div *ngIf="transfers$ | async; let transfers; else loadingTpl">
    <app-checklist *ngIf="transfers?.length > 0" [items]="transfers">
        <div *ngFor="let transfer of transfers">
            ..something here
        </div>
    </app-checklist>
    <ng-container *ngTemplateOutlet="emptyList; context: {length: transfers.length}"></ng-container>
    <ng-container *ngTemplateOutlet="error; context:transfers"></ng-container>
</div>

TransferService.ts:

import { Injectable } from '@angular/core';
import { of } from 'rxjs';

@Injectable()
export class TransfersService {
  transfers$ = of('real observable');
}

component.ts

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { TransfersService } from './TransfersService';

export interface AppResponseError = {code:number,title:string,message:string};
export interface Transfer = {id:number,title:string};

@Component({
  selector: 'app-transfer',
})
export class TransferComponent implements OnInit {
  transfers$: Observable<Transfer[] | AppResponseError>;
  constructor(private transfersService: TransfersService) {
    this.transfers$ = this.transfersService.transfers$;
  }

  ngOnInit() {
    this.transfers$.subscribe((data) => {
      console.log(data);
    });
  }
}

您不需要额外的 *ngIf。

<div *ngIf="transfers$ | async; let transfers; else loadingTpl">

这将做的是等到转账$ | async 已评估,并将结果绑定到 transfers 的值(非美元后缀)。

在 ts 文件中创建以下函数。

isDataAvailable(arr){
 return Array.isArray(arr) && arr.length >0
}

并像这样在模板中使用它

<app-checklist *ngIf="isDataAvailable(transfers)" [items]="transfers"></app-checklist>
<div *ngIf="transfers$ | async; let transfers; else loadingTpl">
        <app-checklist *ngIf="isDataAvailable(transfers)" [items]="transfers"></app-checklist>
        <div *ngFor="let transfer of transfers">
            ..something here
        </div>
    <ng-container *ngTemplateOutlet="emptyList; context: {length: transfers.length}"></ng-container>
    <ng-container *ngTemplateOutlet="error; context:transfers"></ng-container>
</div>