Search code examples
javascriptangularlong-pollingrxjs5angular-http

Infinite polling with Angular 4 and Http observables


I'm trying to build an infinite polling in my Http service because I'm building a king of of dashborad who survey data's comming from a servor, here's my code who's almost working (in my console I see the Json comming but it doesn't reflect to my view...I would like to inject in my users: Observable

const usersURL = 'http://my.super.servor.php'

@Injectable()
export class UserService {

 users: Observable<User[]>

   constructor (public http:Http) {
     this.users = http.get(usersURL)
              genre mobile ou autre
              .map(res => [res.json()]);

        let i = this.users.subscribe(
          usersURL => console.log(usersURL),
         () => {}, // Here we catch up errors
         () => console.log("completed!") // Here we catch up if its completed
        )

    // Here's where I'm trying to do the polling every 5 secondes
    let tick$ = Observable.interval(5000);

    let response$ = 
      tick$
          .flatMap(() => http.get(usersURL))
          .map(res => [res.json()]);

    let stockPoller = response$.subscribe(res => console.log(res));
  }

Solution

  • You just assign your polling observable to this.users:

    this.users = tick$.flatMap(() => http.get(usersURL)).map(res => [res.json()]);