Angular2 http request in interval

I'm trying to make a request every 3 seconds and print the response, but so far no luck :(. I'm new to 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)
  })

  )
    }

      

+3


source to share


1 answer


You need subscribe

to Observable

, which comes from the answer flatMap

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/

cross-domain requests need to be enabled so you can get the data.

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

+4


source







All Articles