Search code examples
angularbrowserbrowser-cache

Is it possible to force hard application update (Ctrl + F5 browser analogue) from the app code in angular?


Sometimes my angular app gets updated. The app is live already and some common scenario of usage is when the user doesn't close the browser tab with the application at all, so outdated version without checks could be used forever.

I've implemented a mechanism to check the app version on the back end side, so all calls from the outdated version are rejected.

The next step is to show the user some "Update required" dialog in case of such back end reject and in case of confirmation, it would be good not to force user press "Ctrl + F5" manually but to do it automatically from the app.

Is it possible?


Solution

  • We need to use interceptor to detect error and if error is detected then we reload page using the window.location.reload(true); it will remove the cache and reload the page.

    @Injectable()
    export class myInterceptor implements HttpInterceptor {
    
      constructor() { }
    
      intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(
          catchError(error => this.handleError(error))
        );
      }
    
      private handleError(error: HttpErrorResponse): Observable<any> {
         if (error.status === 404) {
          // Do your thing here      
         window.location.reload(true);
       }         
      }
    

    I hope it will help you out.