Search code examples
angularobservableangular-httpangular-httpclient

Angular 6: how to get http at an interval


I can't seem to get this solution to work for my code. This is my original code that works without interval. But unfortunately, it makes too many requests.

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

constructor(private http: HttpClient) {}
  ngOnInit() {
  }
  getWeather() {
    this.response = this.http.get<Weather>(this.serviceUrl );
    this.response.subscribe(
      results => {
        this.weathers = results.properties.periods;
        console.log('this.weather ====> ', this.weathers);
      });
    }
}

But now I have errors when I add interval:

ERROR TypeError: Cannot read property 'interval' of undefined

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

constructor(private http: HttpClient) {}
  ngOnInit() {
  }
  getWeather() {
    this.response = this.http.get<Weather>(this.serviceUrl );
    this.response.Observable.interval(60000).subscribe(
      results => {
        this.weathers = results.properties.periods;
        console.log('this.weather ====> ', this.weathers);
      });
    }
}

And I used this following code that doesn't give me any errors, but it still goes into an infinite response as though the interval had no effect.

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { interval } from 'rxjs';
import { take } from 'rxjs/operators';
import { Subject } from 'rxjs';
takeFourNumbers = interval(50000).pipe(take(4));
constructor(private http: HttpClient) {}
  ngOnInit() {
  }
  getWeather() {
    this.response = this.http.get<Weather>(this.serviceUrl );
    this.response.subscribe(
      results => {
        this.weathers = results.properties.periods;
        console.log('this.weather ====> ', this.weathers);
        this.takeFourNumbers.subscribe(x => console.log('Next: ', x));
      });
    }
}

Did something recently change with Angular 6+ where the old solutions don't work any more? I'm new to Angular.


Solution

  • Try as below :

    import { interval } from 'rxjs';
    import { map } from 'rxjs/operators'
    
    interval(50000).pipe(
      map((x) => { /* your code here */ })
    );