Devpop
Devpop

Reputation: 37

how to call a method for every 30 seconds using Angular4 instead of Set interval

HI here i have a method from which i am getting the data here i want that data to be refreshed for every 30 seconds previously i used setINTERVAL method but instead of that can i use Observable Interval if so how can i use this becoz if go out of that page i want to unsubscribe from that method

below is my code which get results

getOrderTrack(data){
    this.serv.OrderTrackDetails(data).subscribe(res=>{

       this.OrderTrack = res.CurrentOrderStatusResult;
       console.log(this.OrderTrack);
     },err=>{
       console.log(err);
     })

Upvotes: 0

Views: 791

Answers (2)

Yerkon
Yerkon

Reputation: 4788

can i use Observable Interval if so how can i use this becoz if go out of that page i want to unsubscribe from that method

You can unsubscribe where you want. So, if you navigate to another page and this component will detroy, thenngOnDestroy lifecycle hook is called.

export class AppComponent {
  name: any = 'Angular 5';
  subscr: Subscription;

  constructor(public http: HttpClient) {

  }

  getData() {
    return this.http.get('https://jsonplaceholder.typicode.com/posts/1');
  }

  ngOnInit() {

    this.subscr = Observable.interval(1000)
      .flatMap(() => this.getData())
      .subscribe(data => {
        console.log('data', data);
        this.name = data;
      });
  }

  unsubscribe() {
    this.subscr.unsubscribe();
  }

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

StackBlitz Demo

Upvotes: 3

Nandita Sharma
Nandita Sharma

Reputation: 13407

Use unsubscribe in the ngDestroy, to unsubscribe the sunbscrition to the observable

@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements OnDestroy {
  private subscription: Subscription;
  this.subscription = // Observable code 
  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

Upvotes: 3

Related Questions