如何将 Firebase 云消息传递 (FCM) 与 Angular 15 结合使用?

Asm*_*oud 6 firebase firebase-cloud-messaging angular

我有一个 Angular 15 项目,我想向其中添加 FCM。

在此输入图像描述

  1. 我安装了 @angular/fire 包..
  2. 像这样将其导入到 app.module 中
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import { provideFirebaseApp, initializeApp } from '@angular/fire/app';
import { getMessaging, provideMessaging } from '@angular/fire/messaging';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    AppRoutingModule,
    provideFirebaseApp(() =>
      initializeApp({
        apiKey: 'AIzaSyDsH-k0rqpA19L1kzVG5tBxPjIIdZOaE1A',
        authDomain: 'labifysystem.firebaseapp.com',
        projectId: 'labifysystem',
        storageBucket: 'labifysystem.appspot.com',
        messagingSenderId: '648676237340',
        appId: '1:648676237340:web:61d9762eddc4291c0c3fd9',
        measurementId: 'G-43TJCGGH4H',
      })
    ),
    provideMessaging(() => getMessaging()),
  ],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

Run Code Online (Sandbox Code Playgroud)

如何在@angular/fire版本^7.5.0中请求权限并获取fcm令牌?

我发现许多教程和文章都使用此语法,但它在版本 7 中不是有效语法,它在 @angular/fire 版本 6 中工作。

import { Component } from '@angular/core';
import { AngularFireMessaging } from '@angular/fire/messaging';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  title = 'fcm-angular-demo';
  message$: Observable<any>;

  constructor(private messaging: AngularFireMessaging) {
    // Request permission to receive notifications
    this.messaging.requestPermission.subscribe(
      () => {
        console.log('Permission granted');
      },
      (error) => {
        console.log('Permission denied', error);
      }
    );

    // Get the current FCM token
    this.messaging.getToken.subscribe(
      (token) => {
        console.log('Token', token);
        // You can send this token to your server and store it there
        // You can also use this token to subscribe to topics
      },
      (error) => {
        console.log('Token error', error);
      }
    );

    // Listen for messages from FCM
    this.message$ = this.messaging.messages;
    this.message$.subscribe(
      (message) => {
        console.log('Message', message);
        // You can display the message or do something else with it
      },
      (error) => {
        console.log('Message error', error);
      }
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

Jak*_*ith 5

解决 @angular/fire 新版本缺乏文档的问题的关键是记住这一点:

新版本的重点是模块化,并试图让您更轻松地仅在捆绑包中包含您想要和需要的内容。因此,如果您需要的话,您可以导入该函数getToken,而不是属于您正在注入的服务的实例,并且您注入的服务不会附带您可能需要或可能不需要的所有可能方法。不仅仅是消息传递是这种情况,还有,等等。getToken FirestoreStorage

例如:

import { Component, inject, OnInit } from '@angular/core';
import { Messaging, getToken, onMessage } from '@angular/fire/messaging';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
  private readonly _messaging = inject(Messaging);
  private readonly _message = new BehaviorSubject<unknown | undefined>(undefined);

  title = 'fcm-angular-demo';
  message$ = this._message.asObservable();

  ngOnInit(): void {
    // Request permission to receive notifications
    Notification.requestPermission().then((permission) => {
      if (permission === 'granted') 
        console.log('Permission granted');
      else if (permission === 'denied')
        console.log('Permission denied');
    });

    // Get the current FCM token
    getToken(this._messaging)
      .then((token) => {
        console.log('Token', token);
        // You can send this token to your server and store it there
        // You can also use this token to subscribe to topics
      })
      .catch((error) => console.log('Token error', error));

    // Listen for messages from FCM
    onMessage(this._message, {
      next: (payload) => {
        console.log('Message', payload);
        // You can display the message or do something else with it
      },
      error: (error) => console.log('Message error', error),
      complete: () => console.log('Done listening to messages')
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

我很遗憾 Angular Fire 的文档在某些方面仍然缺乏最新版本。但是您会开始注意到他们所追求的模式,并且它受到非角度 Web 库变得更加模块化的影响。因此,如果您在 Angular Fire 文档中找不到它,请转到他们的模块化 Web 文档,大部分文档都适用。您可以在此处阅读有关消息传递的更多信息:https ://firebase.google.com/docs/cloud-messaging/js/client