Angular5 PWA doesn't refresh (Service Workers)

一世执手 提交于 2020-05-15 04:46:25

问题


I'm developing an app with angular5, using service workers via the ng-cli, but I realized that after the first time the app shell loads, it doesn't refresh. How can I push new file versions to my app after build it with ng build?. I could directly rewrite the sw.js manually, but as it is generated via the cli, I don't like to affect anything I don't know what is for.

I'm looking for this answer all day, but as service workers are new for the 1.6 version of the ng-cli, I have not found any.

I even found a thread similar thread for angular 4 and a unofficial service workers implementation before ng-cli 1.6, but I don't trust in that approach since it is not official, so I would like to know if you guys could help me find a way to control the way it installs the shell and looks for new versions.

Thank you


回答1:


Here's what worked for me. This helps the browser detect there is a new version of the app.

App.module.ts:

    import { Component } from '@angular/core';
    import { SwUpdate } from '@angular/service-worker';

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {    

      constructor(public updates:SwUpdate) {
        updates.available.subscribe(event => {
          console.log('current version is', event.current);
          console.log('available version is', event.available);
        });
        updates.activated.subscribe(event => {
          console.log('old version was', event.previous);
          console.log('new version is', event.current);
        });

        updates.available.subscribe(event => {
            updates.activateUpdate().then(() => this.updateApp());
        });
       }

       updateApp(){
        document.location.reload();
        console.log("The app is updating right now");

       }
}

And

ngsw.json:

{
  "index": "/index.html",
  "assetGroups": [
    {
      "name": "Your app",
      "installMode": "prefetch",
      "updateMode": "lazy",
      "resources": {
        "files": [
          "/favicon.ico",
          "/index.html",
          "/*.css",
          "/*.js"
        ]
      }
    },
    {
      "name": "assets",
      "installMode": "prefetch",
      "updateMode": "lazy",
      "resources": {
        "files": [
          "/assets/**"
        ],
        "urls":[
          "https://urlsyouwanttocachefrom.com/**",
        ]
      }
    }
  ]
}

This way, every time the app is updated, the browser will autoreload.



来源:https://stackoverflow.com/questions/48146332/angular5-pwa-doesnt-refresh-service-workers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!