div ng如果firestore集合未返回任何文档

时间:2019-04-10 14:55:16

标签: angular google-cloud-firestore angularfire2

我正在使用AngularFire2,我基本上想做的是显示一个div,如果该函数未从某个集合返回任何文档,即为零。如果您返回一个文档或更多文档,则该div应该消失。

我尝试了以下操作,但没有预期的结果:

service.ts

size: number;
contadorSize;

contadorEventosPropios() {
    const user = firebase.auth().currentUser;

    this.contadorSize  = this.afs
        .collection('eventos', ref => ref.where('autorId', '==', user.uid))
        .get().subscribe(snap => {
          this.size = snap.size;
          console.log(this.size);
        });
    return this.contadorSize;
}

component.ts

size: boolean;
contadorSize: number;

constructor( public fs: FirebaseService, private afs: AngularFirestore ) {}

ngOnInit() {
    this.contadorSize = this.fs.contadorEventosPropios();

    if (this.contadorSize === 0 ) {
        return this.size = true;
    } else {
       return this.size = false;
    }
}

component.html

<div *ngIf="size">
  ...
</div>

2 个答案:

答案 0 :(得分:0)

您将返回Subscription对象。您可以将其更改为:

service.ts

size: number;
contadorSize;

contadorEventosPropios(): Observable<number> {
    const user = firebase.auth().currentUser;

    this.contadorSize  = this.afs
        .collection('eventos', ref => ref.where('autorId', '==', user.uid))
        .get()
        .map(snap => { // instead of subscribe
          this.size = snap.size;
          console.log(this.size);
          return snap.size;
        });

    return this.contadorSize;
}

component.ts

size: boolean;
// contadorSize: number; // wrong
contadorSize: Observable<number>; // corrected

constructor( public fs: FirebaseService, private afs: AngularFirestore ) {}

ngOnInit() {
    this.contadorSize = this.fs.contadorEventosPropios();
    // removed
}

component.html async pipe可以解决问题)

<div *ngIf="(contradorSize | async) === 0">
  ...
</div>

答案 1 :(得分:0)

您没有正确处理异步调用。将类型添加到所有变量中是一个好主意,这样可以更轻松地了解意图和错误之处。

尝试将服务更改为以下内容:


contadorEventosPropios(): Observable<{ size: number; }> {
    const user = firebase.auth().currentUser;

    return this.afs
        .collection('eventos', ref => ref.where('autorId', '==', user.uid))
        .get();
}

您的组件类似于:

size: boolean;

constructor( public fs: FirebaseService, private afs: AngularFirestore ) {}

ngOnInit() {
    this.fs.contadorEventosPropios().subscribe(result => {
      if (result.size === 0 ) {
          this.size = true;
      } else {
         this.size = false;
      }
    });