angularfire2-offline icon indicating copy to clipboard operation
angularfire2-offline copied to clipboard

subscription to list query always returns undefined

Open matheus-fatguys opened this issue 7 years ago • 2 comments

I can't unsubscribe from AfoListObservable when I query it because its subscription method always returns undefined.

I have a provider method that querys a list:

Code is bellow:

`

obterCondutorPeloUsuarioLogado(){

let user = this.auth.usuarioLogado();

if(user==null){
  return null;
}

let obs = this.afd.list("condutores", {
  query: {
    orderByChild: "usuario",
    equalTo: user.uid
  }
})
obs.subscribe(condutor=>{
        this.condutor=condutor[0];
});  
return obs;

}

`

Here is my component code subscribing to the list query:

`

let ref= this.fatguysService.obterCondutorPeloUsuarioLogado(); if(ref!=null){ if(this.loading==null){
this.loading = this.loadingCtrl.create({ content: 'Buscando condutor...' }); } else{ this.loading.setContent("Buscando condutor..."); } this.loading.present().then( _=>{ const sub = ref.subscribe( r=>{ sub.unsubscribe();

`

This last line always throws an error cannot read property unsubscribe of undefined.

I noticed that if I comment out the following lines, it works:

// obs.subscribe(condutor=>{ // this.condutor=condutor[0]; // });

matheus-fatguys avatar Aug 22 '17 01:08 matheus-fatguys

I think it's because you are not returning the subscription on obterCondutorPeloUsuarioLogado() method. You are subscribing to the AfoListObservable called obs, but when you return obs, you are not returning the subscription, but only the AfoListObservable reference. To solve the problem, you should subscribe just on client method, like this:

const subscription = this.fatguysService.obterCondutorPeloUsuarioLogado().subscribe(condutor => {
  // Do whatever you need to do with data
});

After that, you'll be able to unsubscribe (subscription.unsubscribe()).

belavenuto avatar Sep 06 '17 13:09 belavenuto

but it shouldn't matter if I subscribe inside the method...

matheus-fatguys avatar Sep 06 '17 16:09 matheus-fatguys