Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...