{"id":21089375,"url":"https://github.com/id1945/ng-service-worker","last_synced_at":"2026-05-21T10:05:07.074Z","repository":{"id":174426704,"uuid":"652220921","full_name":"id1945/ng-service-worker","owner":"id1945","description":"Service worker Angular 16","archived":false,"fork":false,"pushed_at":"2023-06-13T09:43:22.000Z","size":906,"stargazers_count":0,"open_issues_count":0,"forks_count":1,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-01-21T00:50:22.633Z","etag":null,"topics":["angular","pwa","serivceworker","webworker"],"latest_commit_sha":null,"homepage":"https://id1945.github.io/ng-service-worker/","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/id1945.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-06-11T13:27:57.000Z","updated_at":"2023-09-19T14:50:22.000Z","dependencies_parsed_at":"2023-07-08T00:50:35.334Z","dependency_job_id":null,"html_url":"https://github.com/id1945/ng-service-worker","commit_stats":null,"previous_names":["id1945/ng-service-worker"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/id1945%2Fng-service-worker","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/id1945%2Fng-service-worker/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/id1945%2Fng-service-worker/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/id1945%2Fng-service-worker/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/id1945","download_url":"https://codeload.github.com/id1945/ng-service-worker/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243532564,"owners_count":20306157,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["angular","pwa","serivceworker","webworker"],"created_at":"2024-11-19T21:28:36.164Z","updated_at":"2026-05-21T10:05:02.050Z","avatar_url":"https://github.com/id1945.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"Để tạo một service worker trong Angular 16, bạn có thể làm theo các bước sau:\n\nCài đặt service worker bằng cách sử dụng npm:\n\n```\nnpm install --save-dev @angular/service-worker\n```\n\nTạo một file `ngsw-config.json` để cấu hình service worker. Ví dụ:\n\n```json\n{\n  \"index\": \"index.html\",\n  \"assetGroups\": [\n    {\n      \"name\": \"app\",\n      \"installMode\": \"prefetch\",\n      \"resources\": {\n        \"files\": [\n          \"/favicon.ico\",\n          \"/index.html\",\n          \"/manifest.webmanifest\",\n          \"/**/*.css\",\n          \"/**/*.js\"\n        ]\n      }\n    }\n  ],\n  \"dataGroups\": [\n    {\n      \"name\": \"api\",\n      \"urls\": [\n        \"https://api.example.com/data\"\n      ],\n      \"cacheConfig\": {\n        \"strategy\": \"freshness\",\n        \"maxSize\": 100,\n        \"maxAge\": \"1d\",\n        \"maxEntries\": 10\n      }\n    }\n  ],\n  \"navigationUrls\": [\n    \"/**\"\n  ],\n  \"strategy\": \"all\"\n}\n```\n\nThêm mã sau vào file `angular.json` để bao gồm file `ngsw-config.json` trong project:\n\n```json\n\"projects\": {\n  \"my-app\": {\n   ...\n    \"architect\": {\n      \"build\": {\n       ...\n        \"options\": {\n         ...\n          \"assets\": [\n            \"src/favicon.ico\",\n            \"src/index.html\",\n            \"src/manifest.webmanifest\",\n            \"src/**/*.css\",\n            \"src/**/*.js\",\n            \"src/ngsw-config.json\"\n          ]\n        }\n      },\n      \"serve\": {\n       ...\n        \"options\": {\n         ...\n          \"assets\": [\n            \"src/favicon.ico\",\n            \"src/index.html\",\n            \"src/manifest.webmanifest\",\n            \"src/**/*.css\",\n            \"src/**/*.js\",\n            \"src/ngsw-config.json\"\n          ]\n        }\n      }\n    }\n  }\n}\n```\n\nThêm mã sau vào file `app.module.ts` để bao gồm module `ServiceWorkerModule`:\n\n```typescript\nimport { NgModule } from '@angular/core';\nimport { ServiceWorkerModule } from '@angular/service-worker';\nimport { environment } from '../environments/environment';\n\n@NgModule({\n  imports: [\n    ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production })\n  ],\n  providers: [],\n  bootstrap: []\n})\nexport class AppModule { }\n```\n\n\nThêm mã sau vào file `index.html` để bao gồm script để load service worker:\n\n\n```html\n\u003c!doctype html\u003e\n\u003chtml lang=\"en\"\u003e\n\u003chead\u003e\n  \u003cmeta charset=\"utf-8\"\u003e\n  \u003ctitle\u003eMy App\u003c/title\u003e\n  \u003cbase href=\"/\"\u003e\n  \u003cmeta name=\"viewport\" content=\"width=device-width, initial-scale=1\"\u003e\n\u003c/head\u003e\n\u003cbody\u003e\n  \u003capp-root\u003e\u003c/app-root\u003e\n  \u003cscript\u003e\n    if ('serviceWorker' in navigator) {\n      window.addEventListener('load', () =\u003e {\n        navigator.serviceWorker.register('/ngsw-worker.js').then(registration =\u003e {\n          console.log('Service worker registered:', registration);\n        }).catch(error =\u003e {\n          console.log('Service worker registration failed:', error);\n        });\n      });\n    }\n  \u003c/script\u003e\n\u003c/body\u003e\n\u003c/html\u003e\n```\n\nChạy lệnh `ng build` để build project.\n\nSau khi build xong sẽ tự động tạo file `ngsw-worker.js`\n\nKiểm tra bằng cách mở console trong trình duyệt và kiểm tra xem có thông báo \"Service worker registered\" hay không.\n\nĐể tạo một component trong project này ứng dụng service worker để lưu cache data, bạn có thể làm theo các bước sau:\n\nTrong file `about-component.component.ts`, thêm mã sau để lấy dữ liệu từ API và lưu vào cache:\n\n```typescript\nimport { Component, OnInit } from '@angular/core';\nimport { HttpClient } from '@angular/common/http';\n\n@Component({\n    selector: 'app-about',\n    templateUrl: './about.component.html',\n    styleUrls: ['./about.component.css']\n})\nexport class AboutComponent implements OnInit {\n\n    data: any;\n    urlGet = 'https://api.publicapis.org/entries?description=help\u0026Auth=OAuth';\n\n    constructor(private http: HttpClient) { }\n\n    ngOnInit() {\n        if ('caches' in window) {\n            if (navigator.onLine) {\n                console.log('You are connected to the internet');\n                // Fetch API\n                this.http.get(this.urlGet).subscribe(data =\u003e {\n                    console.log('Data loaded from API:', data);\n                    this.data = data;\n                    // Lưu vào cache\n                    caches.open('my-cache').then(cache =\u003e {\n                        cache.put(this.urlGet, new Response(JSON.stringify(data)));\n                    });\n                });\n            } else {\n                console.log('You are not connected to the internet');\n                // Nếu mất internet, bạn có thể lấy dữ liệu từ cache bằng cách sử dụng phương thức caches.match()\n                caches.match(this.urlGet).then(response =\u003e {\n                    if (response) {\n                        response.json().then(data =\u003e {\n                            console.log('Data loaded from cache:', data);\n                            this.data = data;\n                        });\n                    }\n                });\n            }\n\n        }\n    }\n}\n```\n\nTrong file `my-component.component.html`, hiển thị dữ liệu từ API:\n\n```html\n\u003cp\u003e{{ data | json }}\u003c/p\u003e\n```\n\nSau khi hoàn thành các bước trên và deploy, bạn có thể kiểm tra website và ngắt kết nối internet để lấy dữ liệu từ cache.\n\n![124124](https://github.com/id1945/ng-service-worker/assets/40824445/aed2eaea-f341-4f30-a1c2-e26670cc1d17)\n\n\u003cimg width=\"500\" alt=\"sw-architecture\" src=\"https://github.com/id1945/ng-service-worker/assets/40824445/86e812e0-ddb5-4751-9043-bdd1f0361c2c\"\u003e\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fid1945%2Fng-service-worker","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fid1945%2Fng-service-worker","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fid1945%2Fng-service-worker/lists"}