Hguedez
Hguedez

Reputation: 97

Service worker not making request on first load in angular 17

I want to make an API call to one of the endpoints I have inside my main.ts I have done this before to external API's but never to one locally. So, everytime I make the request the first time never loads

It even shows me the error: message : "Http failure during parsing for http://localhost:4200/movies" name : "HttpErrorResponse" ok : false status : 200 statusText : "OK" url : "http://localhost:4200/movies"

But if I reload the page then starts working, I read this in a page as a possible cause: Service workers do not control pages until they become active. This means that a page that loaded the service worker for the first time will not be controlled by the service worker until the page is reloaded. You can use the clients.claim() method in your service worker to take control of the pages as soon as the service worker becomes active.

But I already have this in my service worker:

self.addEventListener('activate', function (event) {
  event.waitUntil(self.clients.claim())
})

Also I added this to my service in order to kind of wait to the service worker to be ready so I can make my requests, but is still not working

getMovies(): Observable<Movie[]> {
    return from(navigator.serviceWorker.ready).pipe(
      switchMap(() => this.http.get<Movie[]>('/movies'))
    );
  }

I feel it has to be something related with the asynchronous request and the service worker to be ready, but not sure

Upvotes: 0

Views: 397

Answers (1)

Hguedez
Hguedez

Reputation: 97

The solution was making an HTTP Request Retry, so If the request fails it will try it again, the only case where is making the retry is on the first load

getMovies(): Observable<Movie[]> {
    return this.http.get<Movie[]>('/movies').pipe(
      retryWhen(errors =>
        errors.pipe(
          delay(1000), // wait 1 second before retrying
          retry(3),
          tap(() => console.log('Retrying...'))
        )
      )
    )
  }

Upvotes: 0

Related Questions