* ng如果div show hide订阅Firestore

时间:2019-04-09 03:02:31

标签: angular google-cloud-firestore

我正在尝试显示div,只要该函数不从特定的Firestore集合(即零)中返回任何文档即可。如果有任何文档,则该div必须隐藏。

有什么想法可以实现吗?我尝试了以下操作,但不起作用:

service.ts

getEventosPropios() {
    const user = firebase.auth().currentUser;
    this.eventosPropios = this.afs.collection('eventos', ref => ref
    .where('autorId', '==', user.uid)
    ).snapshotChanges().pipe(
      map(actions => actions.map(a => {
        const data = a.payload.doc.data() as Evento;
        const id = a.payload.doc.id;
        return { id, ...data };
      }))
    );
    return this.eventosPropios;
  }

component.ts

eventosPropios: any;
eventosLista = true;

constructor( public fs: FirebaseService ) { }

ngOnInit() {
  this.eventosPropios = this.fs.getEventosPropios();
  this.eventosPropios.subscribe(() => this.eventosLista = false);
}

component.html

<div *ngIf="eventosLista">
  ...        
</div>
<div *ngFor="let evento of eventosPropios | async">
  ...
</div>

1 个答案:

答案 0 :(得分:0)

由于您正在对从Subscription方法返回的this.fs.getEventosPropios()进行迭代,因此未显示文档。

稍微更改代码以使用result方法返回的getEventosPropios()应该可以解决此问题。

component.ts

eventosPropiosSub: Subscription; //should be use to unsubscribe later
eventosPropios: any;
eventosLista = true;

constructor( public fs: FirebaseService ) { }

ngOnInit() {
  this.eventosPropiosSub = this.fs.getEventosPropios()
    .subscribe((result) => {
        this.eventosPropios = result; // assign the returned result
        this.eventosLista = false
    });
}