简体   繁体   中英

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)
  })

  )
    }

You need to subscribe to the Observable that comes from the flatMap s 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM