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

nullinjectorerror no provider for broadcast service
swupdate angular
angular service worker
angular service worker communication
angular/pwa
angular custom service worker
swpush
service worker not working on production

Now I know there are a million posts about No Provider for such and such service, I know it needs to go in the providers please read my entire post.

Basically I am trying to use SwUpdate to check to see if there is an update if so, refresh the browser:

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

export class ...

constructor(
    private _swUp: SwUpdate
){} 


ngOnInit() {
    this.checkForUpdate();
}

checkForUpdate() {
    if (this._swUp.isEnabled) {
       this._swUp.available
           .subscribe(() => {
               window.location.reload();
           });
    }
}

now I have registered my serviceworker:

import { ServiceWorkerModule } from '@angular/service-worker'; 
...

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

now when I run my app I get this error:

NullInjectorError: No provider for SwUpdate!

so obviously I try and add it to the providers array in my component module:

import { ServiceWorkerModule, SwUpdate } from '@angular/service-worker'; 
...

imports: [
    environment.production ? ServiceWorkerModule.register('ngsw-worker.js') : [],
],
providers: [
    SwUpdate
]

now this should work but now this time when I run the application I get the following error:

NullInjectorError: No provider for NgswCommChannel!

Now when I try to import NgswCommChannel I get an error saying it does not exist in @angular/service-worker;

I've tried googling around but I cannot find a reference to NgswCommChanel anywhere...

So my question is how can I fix this, or how can I properly use SwUpdate ??

any help would be appreciated

EDIT

I have also tried to do it the EXACT same way it is done in the official angular docs and it is giving me the same error:

constructor(
    updates: SwUpdate
) {
    updates.available
        .subscribe(() => {
            updates.activateUpdate()
                .then(() => document.location.reload());
        });
}

EDIT 2 This is what I get when I run ng -v

Angular CLI: 1.7.4
Node: 10.15.1
OS: win32 x64
Angular: 5.1.2
... animations, common, compiler, compiler-cli, core, forms
... http, platform-browser, platform-browser-dynamic
... platform-server, router

@angular/cli: 1.7.4
@angular/service-worker: 7.2.7
@angular-devkit/build-optimizer: 0.3.2
@angular-devkit/core: 0.3.2
@angular-devkit/schematics: 0.0.40
@ngtools/json-schema: 1.1.0
@ngtools/webpack: 1.10.2
typescript: 2.4.2
webpack: 3.11.0

EDIT 3

Upon further investigation it seems as if you can not use SwUpdate when running your project locally, I saw this article angular-pwa-pitfalls and there solution is to install ng-toolkit, but this just allows you to build your project and then run a mock server, which is pointless because ill lose the ability to develop locally without building the project everytime.

EDIT 4

I changed my app.module.ts to register the service worker:

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

but now I'm getting a whole new bunch of errors

Any other suggestions would be great.

Thanks

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 :)

SwUpdate breaks unit test � Issue #22619 � angular/angular � GitHub, SwUpdate does not work Angular 5 - angular. NullInjectorError: No provider for SwUpdate! so obviously I try and add it to the providers array in my component� SwUpdate does not work Angular 5 Mar 5 '19 5 How to implement Server side pagination using angular 2 Dec 4 '17 5 Angular 2 post method to pass two parameter Jun 24 '16

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!

SwUpdate, [ x] Bug report (nothing found on Github, nor wider web) Current breaks unit test of component with No provider for NgswCommChannel error. core)[ SwUpdate -> NgswCommChannel]: NullInjectorError: No provider for NgswCommChannel! what is swUpdate ? is that a symbol imported from Angular? Stack Overflow Public questions and answers; Teams Private questions and answers for your team; Enterprise Private self-hosted questions and answers for your enterprise; Jobs Programming and related technical career opportunities

For the ones who are getting this error when trying to write unit tests the solution is to add the ServiceWorkerModule to the imports array with the enable to false option when configuring the TestBed:

TestBed.configureTestingModule({
  declarations: [ MyComponent ],
  imports: [
    ServiceWorkerModule.register('ngsw-worker.js', { enabled: false })
  ]
})
.compileComponents();

Angular PWA pitfalls — how to address them with @ng-toolkit, SwUpdate does not work Angular 5. Now I know there are a million posts about No Provider for such and such service, I know it needs to go in� Stack Overflow Public questions and answers; Teams Private questions and answers for your team; Enterprise Private self-hosted questions and answers for your enterprise; Jobs Programming and related technical career opportunities

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

 constructor(private updates: SwUpdate) {}

 ngOnInit(){
     this.updates.available
    .subscribe(() => {
        this.updates.activateUpdate()
            .then(() => document.location.reload());
    });
 }       

Angular's PWA: SwPush and SwUpdate, 5. Add In-app Navigation � 6. Get Data from a Server. Fundamentals class SwUpdate { available: Observable<UpdateAvailableEvent> activated: True if the Service Worker is enabled (supported by the browser and enabled via There are no parameters. Help. Stack Overflow � Gitter � Report Issues � Code of Conduct� I want to use OnsNavigator with angular 6. But wathever I try, I can’t get it to work. If I use OnsNavigator in the constructor of my pagecomponent I get: zone.js:665 Unhandled Promise rejection: StaticInjectorError(AppModule)[OmgevingenpageComponent -> O

Angular Error: "No Provider for Module" | Post, An angular team has done a great job by giving to the developers an ability to extend their Jul 17, 2018 � 5 min read NullInjectorError: No provider for SwPush! Ok, now we know that the problem is with lack of SwPush object in It's an extension for @angular/pwa , which provides SwPush and SwUpdate mockups for�

Angular Service Worker - Step-By-Step Guide, Not too long ago, I wrote an article Your Angular app as Progressive Web App SwPush and SwUpdate are both conveniently exposed in the same Unfortunately, we are unable to interact with it: clicking it does nothing. and start our freshly created server (code is slightly more below or on Github).

User Wesley Coetzee, The error "No Provider for Module" is a common mistake when first starting out, import { BrowserModule } from '@angular/platform-browser'; import { NgModule } Otherwise Angular will not know how to treat the module. Cloud SQL and Cloud RunGoogle Cloud CLI & SDK SetupAWS S3, IAM Group�

Comments
  • Have you tried to check the official documentation of using service worker in Angular?
  • @jess yes... which is why I'm asking why its not working, If the official documentation covered my issue, I would not of posted.
  • did you import your component module to your AppModule ?
  • @JohnVelasquez yes.. everything works fine, then when I put SwUpdate in it crashes the app
  • this only occurs when you're running local right?
  • Did you add the service worker with the command: ng add @angular/pwa --project *project-name*? As that command adds the required steps/commands within the app
  • No I did it manually by following this tutorial my project is Angular 5 and does not support ng add
  • I upgraded my project to angular 7 and ran ng add @angular/pwa and that solved my problem.
  • If you edit your answer to say to update to a later version of angular and run ng add @angular/pwa I will mark this answer as correct since it pointed my in the right direction
  • where is : []coming from, there is no ternary operator in front as I can see, It's throwing error for me.
  • "@angular/cli": "~7.0.5" I try it. but i have the error Invalid rule result: Instance of class Promise.