Angular + Ionic 4,如果可观察的为空,则显示“此处无内容”

时间:2019-11-21 14:19:10

标签: angular typescript ionic-framework rxjs

HTML:

<ion-list>
    <ion-radio-group>
      <ion-item class="ion-no-padding" *ngFor="let service of services | async">
        <ion-label>
          <ion-grid>
            <ion-row>
              <ion-col size="12">
                {{ service.name }}
              </ion-col>
            </ion-row>
          </ion-grid>
        </ion-label>
        <ion-radio slot="end" value="{{ service.id }}"></ion-radio>
      </ion-item>
    </ion-radio-group>
  </ion-list>

和我的page.ts

services: Observable<Service[]>;
// db service conneting to firebase
  ngOnInit() {
    this.services = this.db.getServicesFromVenue(this.routeParams.venueID);
  }

服务:

  getServicesFromVenue(venueID: string): Observable<Service[]> {
    this.serviceCollection = this.afs.collection<Service>('services', ref => ref.where('venue', '==', venueID));
    return this.services = this.serviceCollection
      .snapshotChanges()
      .pipe(
        map(actions => {
          return actions.map(a => {
            const data = a.payload.doc.data();
            const id = a.payload.doc.id;
            return { id, ...data };
          });
        })
      );
  }

一切正常,但是我不知道如何在没有任何结果的情况下显示“无服务”消息。尝试各种方法,但对我没有用:

  <ion-list *ngIf="services | async as service; else noServicesBlock">

什么都不给我

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用nullstartWith(false)值开始,这样它将显示noServicesBlock。还要添加条件检查以查看操作是否为空(空数组的值将为true [])并返回false值。

getServicesFromVenue(venueID: string): Observable<any> {
    this.serviceCollection = this.afs.collection<Service>('services', ref => ref.where('venue', '==', venueID));
    return this.services = this.serviceCollection
      .snapshotChanges()
      .pipe(
        map(actions => {
          if(!actions.length) return false;
          return actions.map(a => {
            const data = a.payload.doc.data();
            const id = a.payload.doc.id;
            return { id, ...data };
          });
        }),
        startWith(false)
      );
  }