Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - stop / cancel / clear observable in routerOnDeactivate() [duplicate]

I'm new to Angular2 so apologies if this is a trivial question. I can't seem to stop interval when I click to a different link. This component fetches data from DB table every 3,5s and it is used as a chat, so 100 users can add to it at any point. I don't want this to run in the background all the time, so I thought I'll use routeronDeactivate() function to make it stop when user is on a different link.

I think I'm doing something wrong. Can anyone help me please?

export class FeedComponent {

    public feeditems: Feed[];
    public timer;


    constructor(private _feedService: FeedService) {
    }

    getArticlesJSON() {

        console.log('getArticlesJSON');
        this._feedService.getFeedJSON()
            .subscribe(
                data => this.feeditems = data,
                err => console.log(err),
                () => console.log('Completed')
            );
    }

    routerOnDeactivate() {

        // this.timer.remove();
        // this.timer.dematerialize();
        // clearInterval(this.timer);

        console.log('-- deactivate ');
        // console.log('-- deactivate ' + JSON.stringify(this.timer));
    }

    routerOnActivate() {

        this.timer = Observable.timer(5000,3500);
        this.timer.subscribe(() => {
            this.getArticlesJSON();
        });

        console.log('++ activate ' + JSON.stringify(this.timer));
    }
}
like image 643
Lukas C Avatar asked Apr 13 '16 13:04

Lukas C


1 Answers

routerOnActivate() {
  this.timer = Observable.timer(5000,3500);
  this.subscription = this.timer.subscribe(() => {
    this.getArticlesJSON();
  });
}

routerOnDeactivate() {
  this.subscription.unsubscribe();
}
like image 91
Günter Zöchbauer Avatar answered Nov 07 '22 20:11

Günter Zöchbauer