在名为bd的服务中,我有一个名为ConsultaPublicacoes的方法,该方法返回我在Firebase数据库上拥有的,用于特定用户电子邮件的所有发布。
bd.service
public consultaPublicacoes(email:string):Observable<any>{
return this.checkarPublicacoes=new Observable((observer)=>{
firebase.database().ref(`publicacoes/${btoa(email)}`)
.orderByKey()
.once('value')
.then((snapshot:any)=>{
let publicacoes:Array<Publicacao>=[]
snapshot.forEach((childSnapshot:any) => {
let publicacao=childSnapshot.val()
publicacao.key=childSnapshot.key
publicacoes.push(publicacao)
});
return publicacoes.reverse()
}).then((publicacoes:any)=>{
publicacoes.forEach((publicacao)=>{
firebase.storage().ref().child(`imagens/${publicacao.key}`).getDownloadURL()
.then((url:string)=>{
publicacao.url_imagem=url
firebase.database().ref(`usuario_detalhe/${btoa(email)}`).once('value')
.then((snapshot:any)=>{
publicacao.nome_usuario=snapshot.val().nome_usuario
})
})
})
observer.next(publicacoes)
})
})
我在publicacoesComponent上还有一个名为atualizarTimeLine()的方法,该方法负责将从Observable返回的数据关联到名为this.publicacoes(PublicacoesComponent)的变量中。
PublicacoesComponent
export class PublicacoesComponent implements OnInit, OnDestroy {
public email:string
public publicacoes:Publicacao[];
public gostou:boolean=false;
constructor(private bd:Bd) { }
ngOnInit() {
firebase.auth().onAuthStateChanged((user)=>{
if(user!=null){
this.email=user.email
this.atualizarTimeLine()
}
})
this.atualizarTimeLine();
}
public atualizarTimeLine(){
console.log("atualizarTimeLine from publicacoes")
this.bd.consultaPublicacoes(this.email)
.subscribe((publicacoes:any)=>{
console.log(publicacoes)
this.publicacoes=publicacoes
})
}
....
MenuComponent
export class MenuComponent implements OnInit {
email: string;
constructor(private bd:Bd, private router:Router, private autenticacao:Autenticacao) { }
ngOnInit() {
firebase.auth().onAuthStateChanged((user)=>{
if(user!=null){
this.email=user.email
this.atualizarTimeLine()
}
})
this.atualizarTimeLine()
}
atualizarTimeLine(){
console.log("atualizarTimeLine From MenuComponent")
this.bd.consultaPublicacoes(this.email)
//this.router.navigate(['/home']);
}
我希望每次从MenuComponent(this.bd.consultaPublicacoes())调用ConsultaPublicacoes时都能够更新(publicacoesComponent的)变量publicacoes的值,该怎么办?在ConsultaPublicacao中观察到的最佳选择吗?
答案 0 :(得分:1)
只需使用.db.service这样的'Subject':firebaseSubject = new Subject()。在ConsultaPublicacoes函数中:firebaseSubject.next(publicacoes)。 publicacoesComponent:firebaseSubject.subscribe((publicacoes)=> {})。 MenuComponent:this.atualizarTimeLine();