NullInjectorError: No provider for SwUpdate! SwUpdate does not work Angular 5

吃可爱长大的小学妹 提交于 2019-12-05 09:43:38

Your issue is in the app.module.ts.

You need to import your service worker like this:

imports: [
    ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production }) : [],
],

The code you had before was only including the module when you were in production mode, so during development it wasn't including the module at all.

EDIT:

Inside my app.component.ts I have:

constructor(private swUpdate: SwUpdate) { }

ngAfterViewInit() {
  if (this.swUpdate.isEnabled) {
    this.swUpdate.available
      .subscribe(() => {
        this.swUpdate
          .activateUpdate()
          .then(() => {
            window.location.reload();
          });
      });
  }
}

EDIT:

As per your comment, updating to latest version of Angular fixed your issue, it's nice they've made upgrading so simple now :)

After much research it seems like it was an issue with angular 5.2.1 so..

I upgraded my project to angular 7, ran ng add @angular/pwa and that solved my problem!

Try below code, Add update into ngOnInit() method.

 constructor(private updates: SwUpdate) {}

 ngOnInit(){
     this.updates.available
    .subscribe(() => {
        this.updates.activateUpdate()
            .then(() => document.location.reload());
    });
 }       
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!