I have installed :
"@angular/fire": "^18.0.1",
My 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));
Then i initializeApp in my app.config.ts :
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(),
]
};
And then i try to listen to notifications in my 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;
})
}
And i get the following error - why ? :
Firebase: No Firebase App '[DEFAULT]' has been created - call initializeApp() first (app/no-app).
As stated in the documentation here, you should inject Messaging
instead of calling getMessage:
constructor(private msg: Messaging){
Notification.requestPermission().then(
(notificationPermissions: NotificationPermission) => {
if (notificationPermissions === "granted") {
console.log("Granted");
}
if (notificationPermissions === "denied") {
console.log("Denied");
}
});