2

I try send http-request. I use angular 2 and rxjs library. I need send a request with a period of 5 seconds.

At first i import operator and use it follow:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
// import { interval } from 'rxjs/observable/interval';
import 'rxjs/add/observable/interval';

@Injectable()
export class TasksService {
  constructor(private http: HttpClient) { };
  getUserTasks(userId): Observable<any> {
    return this.http.interval(5000).get('http://127.0.0.1:8000/app_tasks/user_tasks?user_id=' + userId);
  };
}

Secondly i subscribe in component:

ngOnInit() {
  let userId = 1;
  this.getUserTasks(userId);
}

private getUserTasks(userId): void {  
  this.tasksService.getUserTasks(userId).subscribe(
    data => {   
      this.userTasks = JSON.parse(data);                 
      console.log('userTasks', this.userTasks);
    }
  )
};

But consoe display follow error message:

ERROR in src/app/services/tasks.service.ts(16,21): error TS2339: Property 'interval' does not exist on type 'HttpClient'.

Mark van Straten
  • 9,287
  • 3
  • 38
  • 57
provoter33
  • 119
  • 2
  • 7

3 Answers3

4

Interval is a creator function for an Observable, not HttpClient. I would try the following:

Observable.interval(5000)
  .switchMap(_ => this.http.get('http://127.0.0.1:8000/app_tasks/user_tasks?user_id=' + userId)

By using .switchMap you will abandon the previous http.get result if a new interval is hit before your previous request returns (5 seconds, hope that does not happen).

Mark van Straten
  • 9,287
  • 3
  • 38
  • 57
0

I think on Angular 4+ you should use IntervalObservable for this. You can read more about version changes on this old question (Angular2+ http at an interval) or use right answer @Ploppy https://stackoverflow.com/a/40285206/5319874

Denis Savenko
  • 829
  • 1
  • 13
  • 29
0

According to accepted answer. switchMap will not be the best idea if request takes more than 5 seconds. As alternative I'd rather suggest exhaustMap:

Observable.interval(5000)
 .exhaustMap(_ => this.http.get(`http://127.0.0.1:8000/app_tasks/user_tasks?user_id=${userId}`)

It will not cancel pending request after 5 seconds but ignore any request until pending request either fails or returns value. But it depends on your case.

krystianpe
  • 136
  • 3