adriancarriger / angularfire2-offline

🔌 A simple wrapper for AngularFire2 to read and write to Firebase while offline, even after a complete refresh.
https://angularfire2-offline.firebaseapp.com/
MIT License
207 stars 48 forks source link

subscription to list query always returns undefined #64

Open matheus-fatguys opened 7 years ago

matheus-fatguys commented 7 years ago

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]; // });

belavenuto commented 7 years ago

I think it's because you are not returning the subscription on obterCondutorPeloUsuarioLogado() method. You are subscribing to the AfoListObservablecalled obs, but when you return obs, you are not returning the subscription, but only the AfoListObservablereference. 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()).

matheus-fatguys commented 7 years ago

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