Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular service worker offline caching is not working when I've deployed in server

When I built my angular project with angular/pwa and tested it on local server using http-server, it was working as expected. Even offline caching is working fine in local.

But when I've deployed the same thing in server, I was able to install and run it on any device but not able to open when I am offline.

service-workers are not caching the contents in angular pwa

Here's my app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { GetchucknorrisjokesService } from './getchucknorrisjokes.service';
import { ServiceWorkerModule } from '@angular/service-worker';
import { environment } from '../environments/environment';

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production })
  ],
  providers: [ GetchucknorrisjokesService ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Here's my ngsw-config.json file

{
  "$schema": "./node_modules/@angular/service-worker/config/schema.json",
  "index": "/index.html",
  "assetGroups": [
    {
      "name": "app",
      "installMode": "prefetch",
      "resources": {
        "files": [
          "/favicon.ico",
          "/index.html",
          "/*.css",
          "/*.js"
        ]
      }
    }, {
      "name": "assets",
      "installMode": "lazy",
      "updateMode": "prefetch",
      "resources": {
        "files": [
          "/assets/**",
          "/*.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)"
        ]
      }
    }
  ]
}
like image 827
Vinay Nvd Avatar asked Mar 04 '23 21:03

Vinay Nvd


1 Answers

Update your serivce worker like this by removing $schema, my configuration is the same as your

{
  "index": "/index.html",
  "assetGroups": [
    {
      "name": "app",
      "installMode": "prefetch",
      "resources": {
        "files": [
          "/favicon.ico",
          "/index.html",
          "/*.css",
          "/*.js"
        ]
      }
    }, {
      "name": "assets",
      "installMode": "lazy",
      "updateMode": "prefetch",
      "resources": {
        "files": [
          "/assets/**",
          "/*.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)"
        ]
      }
    }
  ]
}

You have the problem because when you build into production mode your code is looking for this file ./node_modules/@angular/service-worker/config/schema.json

So your service worker will not work

like image 136
Tony Ngo Avatar answered Mar 09 '23 01:03

Tony Ngo