angularfire icon indicating copy to clipboard operation
angularfire copied to clipboard

how we can do unsubscribe in the component

Open samirthebti opened this issue 10 years ago • 14 comments

I can find the unsubscribe method , any help ?

samirthebti avatar Jul 21 '16 23:07 samirthebti

Not sure what you mean here. You should be more clear when asking for help, but since I've experienced a similar issue before I'm gonna assume you are not finding the unsubscribe method after declaring the FirebaseObservable:

const firebaseObservable = this.af.database.object('/item');

//then, you are trying to:

firebaseObservable.unsubscribe(); //doesn't work

If that's the case, then you should know that you can't unsubscribe directly from FirebaseObjectObservable or FirebaseListObservable. You must subscribe to it first so you can have a subscription returned to you.

let objectSubscription = this.af.database.object('/item').subscribe(data=>{ 
   //do something
});

// Later somewhere in your code, you can then:
objectSubscription.unsubscribe();

lf-alves avatar Jul 22 '16 18:07 lf-alves

@lf-alves Thank you , that's what i asked for .

samirthebti avatar Jul 22 '16 20:07 samirthebti

Hello in the documentation of retrieving data as lists mentioned this method

this.items = af.database.list('/items', { preserveSnapshot: true });
this.items
  .subscribe(snapshots => {
    snapshots.forEach(snapshot => {
      console.log(snapshot.key)
      console.log(snapshot.val())
    });
  })

how we can unsubscribe . I think that unsubscribe method not existed yet @lf-alves

samirthebti avatar Jul 23 '16 23:07 samirthebti

this.items = af.database.list('/items', { preserveSnapshot: true });
this.itemsSubscription = this.items
  .subscribe(snapshots => {
    snapshots.forEach(snapshot => {
      console.log(snapshot.key)
      console.log(snapshot.val())
    });
  })

//Later, somewhere
this.itemsSubscription.unsubscribe();

The unsubscribe method is only available to the Subscription, not to the Observable itself.

lf-alves avatar Jul 23 '16 23:07 lf-alves

thank you @lf-alves so what the solution ? because i get the duplicated result of query when i refresh the component or when i get to another component and back to the component contain the query .

samirthebti avatar Jul 24 '16 00:07 samirthebti

Ok, I think I see your problem. Just make sure you unsubscribe to the query when your component gets destroyed.

Add this to the component that contains the query:

ngOnDestroy(){
this.itemsSubscription.unsubscribe();
}

If you could provide a plnkr or something similar, it would be easier to help you out. I'm just guessing stuff here.

lf-alves avatar Jul 24 '16 00:07 lf-alves

@lf-alves I solve the problem by using this code :

ngOnDestroy(){
  this.itemsSubscription.subscribe().unsubscribe();
}

FirebaseListObservable don't have the unsubscribe () methode , i used the subscribe unsubscribe () methode and she work fine for me , Thanks @lf-alves for your help

samirthebti avatar Jul 24 '16 00:07 samirthebti

This is the correct approach: //could by a Observable or FirebaseListObservable `this.items = af.database.list('/items' ); this.sub = this.itemsSubscription = this.items .subscribe(snapshots => { this.items = snapshots }); })

//Later, somewhere ngOnDestroy(){ this.sub.unsubscribe(); }`

mpeguero avatar Nov 17 '16 17:11 mpeguero

To obtain behavior like once():

var sub = this.items.subscribe(snapshots => {
    console.log(snapshots);
    sub.unsubscribe();
});

Or a bit prettier:

import 'rxjs/add/operator/first';
this.items.first().subscribe(snapshots => console.log(snapshots));

katowulf avatar Nov 17 '16 23:11 katowulf

Does this work? In beta5 i couldn't make in working because the observables never complete (i think). I'm using the take-operator for this:

import 'rxjs/add/operator/take';
this.items.take(1).subscribe(snapshots => console.log(snapshots));

chrste90 avatar Nov 18 '16 08:11 chrste90

const obj: Observable = this.af.database.object('/items/'+item.id); obj.subcribe(item => console.log(item);

this should works


From: Chris1308 [email protected] Sent: Friday, November 18, 2016 3:55:54 AM To: angular/angularfire2 Cc: Miguel Peguero; Comment Subject: Re: [angular/angularfire2] how we can do unsubscribe in the component (#377)

Does this work? In beta5 i couldn't make in working because the observables never complete (i think). I'm using the take-operator for this:

import 'rxjs/add/operator/take'; this.items.take(1).subscribe(snapshots => console.log(snapshots));

You are receiving this because you commented. Reply to this email directly, view it on GitHubhttps://github.com/angular/angularfire2/issues/377#issuecomment-261480358, or mute the threadhttps://github.com/notifications/unsubscribe-auth/ABvDp3NCWkv-mgCr7gSgyMqKCFELoSU8ks5q_WgagaJpZM4JSTW2.

mpeguero avatar Nov 22 '16 21:11 mpeguero

This took me some time to figure out, one person suggested firebase.database().goOffline() which does work but is clearly blunt force.

Apparently, you can not unsubscribe from an Observable.

The correct way of doing this is making "subscription" and unsubscribing from this.

  constructor(

  //check if we are logged into firebase using OAuth and because its a subscription will change even if we are not on the current page, this should be in a service/provider

  this.AngularFireAuth.authState.subscribe(user => {

    if (user && user.uid) {
      this.userloggedin = true;
      //firebase.database().goOnline();
    }else{
      this.userloggedin = false;
      //firebase.database().goOffline();
    }
  });
  
}

ViewWillEnter(){
  try{

    this.items = this.AngularFireDatabase.list("my firebase DB tree", ref => ref.limitToLast(50)).valueChanges();

    this.subscription = this.p.subscribe(res => {

      //keep watching
      if(this.authData.userloggedin == false || !res){ 
      
      if(this.subscription !== undefined){
      
        this.subscription.unsubscribe();
        
        console.log(this.subscription);
        
        this.subscription = undefined;
        
      }
        
      

        
        
      }

    });

  } catch(e) {
    console.error(e);
  }
}

or if you like, kill the subscription when leaving the page...

OnDestroy(){

  if(this.subscription !== undefined){
    this.subscription.unsubscribe();
    this.subscription = undefined;
  }

}

developerndm avatar Mar 27 '18 11:03 developerndm

this.currentGroupData = this.groupservice.getGroupsMessages(groupId);

This.sub = this.currentGroupData.snapshotChanges().subscribe(data => {

});

onDestroy(){

this.sub.unsubscribe()

}

Sent from Mailhttps://go.microsoft.com/fwlink/?LinkId=550986 for Windows 10


From: Sagar Doshi [email protected] Sent: Friday, April 19, 2019 4:11:05 AM To: angular/angularfire2 Cc: Miguel Peguero; Comment Subject: Re: [angular/angularfire2] how we can do unsubscribe in the component (#377)

Hello @lf-alveshttps://github.com/lf-alves ,

I have review your comment above related to unsubscribe FirebaseListObservable , And use same method on project but not working.

I will share all details bellow:

Created Service: group.service.ts

import { AngularFireDatabase, AngularFireList, AngularFireObject } from '@angular/fire/database';

export class GroupService {

public getGroupData: AngularFireList;

constructor(public fdb: AngularFireDatabase) { this.getGroupData = this.fdb.list('/groups/'+groupname+'/msgboard/', ref => ref.limitToLast(10).orderByKey()); return this.getGroupData; }

On component: index.component.ts

this.currentGroupData = this.groupservice.getGroupsMessages(groupId); this.currentGroupData.snapshotChanges().subscribe(data => { })

this.currentGroupData.unsubscribe(); // Not Working when change "groupid" New Group record come but last Subscription can't stop.

So please help me on this.

Thanks Sagar Doshi

— You are receiving this because you commented. Reply to this email directly, view it on GitHubhttps://github.com/angular/angularfire2/issues/377#issuecomment-484802312, or mute the threadhttps://github.com/notifications/unsubscribe-auth/AAN4HJYEWGSBTIG5ZOCEJDDPRF5BTANCNFSM4CKJGW3A.

mpeguero avatar Apr 22 '19 18:04 mpeguero

Hello, I need help.

I have the same problem, when I refresh the page or navigate back to the same component where the query was first executed, I get a duplicate result. Even if I run this.itemsSusbcribe.unsubscribe() when the component is destroyed.

daatky avatar Mar 15 '21 22:03 daatky