Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
430 views
in Technique[技术] by (71.8m points)

typescript - HTTP request in an interval doesn't work Angular 10

I'm working on Angular 10 with function of checking connectivity by keep sending a request to the server every 5 seconds.

The problem is the request doesn't really sent out, it just keep console.warn every 5 seconds.

The problem only occurs when response responded with status 200, if responded with status 404, it works. Once it responded with status 200, it won't send any HTTP request in every 5s and just print out the previous http request's data.

PS: I'm testing on localhost server

Here is my code

checkConnection(): Subscription {
    return interval(2000)
      .subscribe(
        x => {
          this.httpService.testConnectivity().subscribe(
            data => console.warn(`Success: ${data}`),
            error => console.warn(`Error: ${error}`),
            () => console.warn("Completed")
          )
        }
      );
}

The testConnectivity function as below

testConnectivity(): Observable<any> {
    if (isPlatformBrowser(this.platformId)) {
      return this.http
        .get(`${this.url}/api/testconnection`, { observe: 'response' })
        .pipe(
          catchError(this.handleError)
        );
    }
  }
question from:https://stackoverflow.com/questions/66061888/http-request-in-an-interval-doesnt-work-angular-10

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I found the problem. The problem is the HTTP request was cached by the browser.

In order to making a refresh request. Simply add ?x where x is some unique number after the url (Eg: http://localhost:3000/api/testconnection?0) on every request.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...