How to prevent Browser cache on Angular 2 site?

后端 未结 6 1609
慢半拍i
慢半拍i 2020-12-04 05:37

We\'re currently working on a new project with regular updates that\'s being used daily by one of our clients. This project is being developed using angular 2 and we\'re fac

6条回答
  •  生来不讨喜
    2020-12-04 06:11

    A combination of @Jack's answer and @ranierbit's answer should do the trick.

    Set the ng build flag for --output-hashing so:

    ng build --output-hashing=all
    

    Then add this class either in a service or in your app.module

    @Injectable()
    export class NoCacheHeadersInterceptor implements HttpInterceptor {
        intercept(req: HttpRequest, next: HttpHandler) {
            const authReq = req.clone({
                setHeaders: {
                    'Cache-Control': 'no-cache',
                     Pragma: 'no-cache'
                }
            });
            return next.handle(authReq);    
        }
    }
    

    Then add this to your providers in your app.module:

    providers: [
      ... // other providers
      {
        provide: HTTP_INTERCEPTORS,
        useClass: NoCacheHeadersInterceptor,
        multi: true
      },
      ... // other providers
    ]
    

    This should prevent caching issues on live sites for client machines

提交回复
热议问题