Angular 11中动态更新firebase-messaging-sw.js的实现方案咨询
Angular 11 动态配置Firebase推送通知(多环境支持)
1. 配置多环境Firebase参数
在src/environments目录下,为每个环境单独定义Firebase配置:
// src/environments/environment.ts(开发环境) export const environment = { production: false, firebase: { apiKey: '你的开发环境API_KEY', authDomain: '你的开发环境AUTH_DOMAIN', projectId: '你的开发环境PROJECT_ID', messagingSenderId: '你的开发环境SENDER_ID', appId: '你的开发环境APP_ID' } };
// src/environments/environment.prod.ts(生产环境) export const environment = { production: true, firebase: { apiKey: '你的生产环境API_KEY', authDomain: '你的生产环境AUTH_DOMAIN', projectId: '你的生产环境PROJECT_ID', messagingSenderId: '你的生产环境SENDER_ID', appId: '你的生产环境APP_ID' } };
2. 改造Service Worker接收动态配置
创建/修改你的Firebase消息Service Worker文件(比如src/firebase-messaging-sw.js),添加消息监听逻辑来接收主应用传递的配置:
// 存储全局Firebase配置 let firebaseConfig = null; // 监听来自主应用的配置消息 self.addEventListener('message', (event) => { if (event.data?.type === 'SET_FIREBASE_CONFIG') { firebaseConfig = event.data.config; // 配置就绪后初始化Firebase initFirebaseMessaging(); } }); // 激活Service Worker时,若已有配置则初始化 self.addEventListener('activate', (event) => { event.waitUntil( Promise.resolve().then(() => { if (firebaseConfig) { initFirebaseMessaging(); } }) ); }); // 初始化Firebase消息服务 function initFirebaseMessaging() { if (!firebaseConfig) return; // 导入对应版本的Firebase SDK(需与主应用版本一致) importScripts('https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js'); importScripts('https://www.gstatic.com/firebasejs/8.10.0/firebase-messaging.js'); firebase.initializeApp(firebaseConfig); const messaging = firebase.messaging(); // 处理后台推送消息 messaging.onBackgroundMessage((payload) => { const notificationTitle = payload.notification?.title || '新通知'; const notificationOptions = { body: payload.notification?.body || '您有一条新消息', icon: '/assets/icons/icon-192x192.png' // 替换为你的通知图标路径 }; self.registration.showNotification(notificationTitle, notificationOptions); }); }
3. 主应用传递配置给Service Worker
在app.component.ts中,当Service Worker就绪或更新时,将当前环境的Firebase配置传递过去:
import { Component, OnInit } from '@angular/core'; import { SwPush } from '@angular/service-worker'; import { environment } from '../environments/environment'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { constructor(private swPush: SwPush) {} ngOnInit(): void { this.swPush.available.subscribe(() => { navigator.serviceWorker.ready.then(registration => { // 发送配置给当前激活的Service Worker this.sendFirebaseConfig(registration.active); // 监听Service Worker更新,新Worker激活后重新发送配置 registration.addEventListener('updatefound', () => { const newWorker = registration.installing; newWorker?.addEventListener('statechange', () => { if (newWorker.state === 'activated') { this.sendFirebaseConfig(newWorker); } }); }); }); }); } private sendFirebaseConfig(worker: ServiceWorker | null): void { if (worker) { worker.postMessage({ type: 'SET_FIREBASE_CONFIG', config: environment.firebase }); } } }
4. 调整Angular构建配置
确保angular.json中正确配置环境文件替换和Service Worker资源:
"projects": { "你的项目名称": { "architect": { "build": { "options": { "serviceWorker": true, "ngswConfigPath": "src/ngsw-config.json", "assets": [ "src/favicon.ico", "src/assets", "src/firebase-messaging-sw.js" // 将Service Worker文件加入静态资源 ] }, "configurations": { "production": { "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.prod.ts" } ], // 其他生产环境配置 } } } } } }
5. 测试多环境配置
- 开发环境构建:
ng serve,主应用自动传递开发环境Firebase配置给Service Worker - 生产环境构建:
ng build --prod,构建后自动替换为生产环境配置
内容的提问来源于stack exchange,提问作者Tushar Shekokar
相关产品推荐
相关产品推荐

