How to handle custom code in Ngsw - in Fetch event

535 views Asked by At

I was having service worker implemented in angular.js application where we have some custom code written in self.addEventListener('fetch', function (event) . Now i am planning to migrate the application to angular, and i found in angular we have the special plugin which will do all configuration and cache cleanup. "@angular/service-worker": "~10.0.6",.

Now i am suffering to have the custom code implemented inside fetch event to integrate in angular version. Is there any way we can have the fetch method override in to a component and do the operation from there.

1

There are 1 answers

0
Luis Reinoso On

Based on your message this steps were done using [email protected].

Edit service worker file.

  • Open the file <project_name>/node_modules/@angular/service-worker/ngsw-worker.js
  • Search handleFetch function Line 1121.
  • Edit adapt that function with your requirement. Check out handleFetchWithFreshness and handleFetchWithPerformance as examples.
  • Save

Patch file

  • Use patch-package to save patch.npx patch-package @angular/service-worker
  • Make a commit.
  • Add postinstall script to package.json
"scripts": {
 "postinstall": "patch-package"
}
  • Add patch-package package npm install --save-dev patch-package

Test service worker

  • ng build.
  • start a server of dist files.
  • it should works.