tlq
tlq

Reputation: 991

Angular2 http request in an interval

I m trying to make a request every 3 seconds and print out the response but until now no luck :( . I m pretty new to the Observables, so what am I doing wrong ?

checkConnection() {

const URL = "https://www.google.at/";

Observable.interval(3000)
  .flatMap(() => this.http.get(URL).map(res => res.json()).catch((error:any) => Observable.throw(error.json().error || 'Server error'))
  .subscribe(data => {
     console.log(data)
  })

  )
    }

Upvotes: 3

Views: 2362

Answers (1)

eko
eko

Reputation: 40677

You need to subscribe to the Observable that comes from the flatMaps response like this:

Observable.interval(3000)
      .flatMap(() => this.http.get(URL)
      .map( res => res.json() )
      .catch( (error:any) => Observable.throw(error.json().error || 'Server error') ) )
      .subscribe(data => {
         console.log(data)
      })

And https://www.google.at/ needs to enable cross-domain requests in order for you to get the data.

Example plunker that you can work on: http://plnkr.co/edit/Nz0LZJDSPcUZlYOHU3p7?p=preview

Upvotes: 3

Related Questions