我已经安装了:
"@angular/fire": "^18.0.1",
我的main.ts:
import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent, appConfig)
.catch((err) => console.error(err));
然后我在 app.config.ts 中初始化App:
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes, inMemoryScrollingFeature),
provideAnimations(),
provideStore(reducers),
provideFirebaseApp(() => initializeApp(environment.firebaseConfig)),
provideMessaging(() => getMessaging()),
provideEffects([]),
provideRouterStore(),
provideHttpClient(withFetch(), withInterceptors([mainInterceptor])),
MessageService,
provideStoreDevtools({ maxAge: 25, logOnly: !isDevMode() }),
provideServiceWorker('ngsw-worker.js', {
enabled: !isDevMode(),
registrationStrategy: 'registerWhenStable:30000'
}), provideAnimationsAsync(),
]
};
然后我尝试在我的 app.component.ts 中收听通知:
ngOnInit(): void {
if(this.platform.isBrowser){
this.requestPermission();
this.listen();
}
}
requestPermission() {
const messaging = getMessaging();
getToken(messaging, {
vapidKey: environment.vapidKey
}).then(
(currentToken) => {
if (currentToken) {
console.log('Your token is: ', currentToken);
} else {
console.log('No registration token available. Request permission to generate one.');
}
}
).catch((error) => {
console.log('An error occurred while retrieving token. ', error.message);
})
}
listen() {
const messaging = getMessaging();
onMessage(messaging, (payload) => {
console.log('Message received. ', payload);
this.message = payload;
})
}
我收到以下错误 - 为什么? :
Firebase:未创建 Firebase 应用程序“[DEFAULT]” - 调用 首先initializeApp()(应用程序/无应用程序)。
如文档中所述here,您应该注入
Messaging
而不是调用getMessage:
constructor(private msg: Messaging){
Notification.requestPermission().then(
(notificationPermissions: NotificationPermission) => {
if (notificationPermissions === "granted") {
console.log("Granted");
}
if (notificationPermissions === "denied") {
console.log("Denied");
}
});