简体   繁体   English

一次可观察到的Firestore的angularfire2订阅

[英]angularfire2 for firestore observable subscribing once at a time

I want make a firestore get items observable. 我想让消防站获得可观察的物品。 But the problem is it subscribes once a time. 但是问题是它一次订阅一次。 Below is my code: 下面是我的代码:

In provider: 在提供者中:

this.allSponser = this.afs.collection<Sponsoremphasized text('sponsors').snapshotChanges().pipe(map(actions => { 
    return actions.map(a => 
    { 
        const data = a.payload.doc.data() as Sponsor; 
        data.id = a.payload.doc.id; 
        return data; 
    }); 
})); 

in signup page: 在注册页面中:

this.allSponser.subscribe(data=>{ console.log(data); }) 

printing for the first time of load if I am goingback to any other page and coming back to again signup it is not printing. 如果我要返回任何其他页面并再次进行注册,则在第一次加载时打印,这不是打印。

First of all just mentioning when you navigate away from your component it will destroyed and will recreated, so keep that in your mind, you need to subscribe to observables in ngOnInit and unsubscribe in 'ngOnDestroy' 首先,只需提及离开组件时它会被破坏并会重新创建,因此请记住,您需要在ngOnInit unsubscribe observables ngOnInit而在ngOnInit unsubscribe

The other point is I usually return the observalbe from my service something like this 另一点是我通常会从我的服务中返回observalbe

getSoponsors() {
return this.afs.collection<Sponsoremphasizedtext>('sponsors').snapshotChanges().pipe(map(actions => { 
    return actions.map(a => 
    { 
        const data = a.payload.doc.data() as Sponsor; 
        data.id = a.payload.doc.id; 
        return data; 
    }); 
})); 
}

then in my component 然后在我的组件中

isAlive: boolean = true

ngOnInit() {
  this.service.getSoponsors()
    .pipe(takeWhile(() => this.isAlive))
    .subscribe(data => ...)
}

ngOnDestroy() {
  this.isAlive = false;
}

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

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