In my bd service, there is a method called consultaPublicacoes that retrieves all publications from the Firebase database for a specific user email.
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)
})
})
The PublicacoesComponent has a method called atualizarTimeLine() responsible for assigning the data returned by the Observable to a variable named this.publicacoes.
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("Updating TimeLine in 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("Updating TimeLine From MenuComponent")
this.bd.consultaPublicacoes(this.email)
//this.router.navigate(['/home']);
}
I am looking for a way to update the value of the publicacoes variable in the PublicacoesComponent every time consultaPublicacoes is called from the MenuComponent. Is using an observable in consultaPublicacao the best option for this scenario?