代码之家  ›  专栏  ›  技术社区  ›  Asmaa Mahmoud

如何在Angular 15中使用firebase云消息(FCM)?

  •  1
  • Asmaa Mahmoud  · 技术社区  · 2 年前

    我有一个角度15项目,我想添加FCM。

    enter image description here

    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 {}
    
    

    如何在@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);
          }
        );
      }
    }
    
    0 回复  |  直到 2 年前
        1
  •  5
  •   Jake Smith    2 年前

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

    新版本完全是模块化的,并试图让它更容易在捆绑包中只包含您想要和需要的内容。所以不是 getToken 属于要注入的服务的实例,则导入 getToken 作用 ,如果您需要它,并且您的注入服务并没有提供您可能需要或不需要的所有可能方法。不仅是消息传递,而且 Firestore , Storage

    例如

    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')
        );
      }
    }
    

    令我沮丧的是,Angular Fire的文档在某些方面仍然缺乏最新版本的文档。但你会开始注意到他们所追求的模式,它受到非角度网络库变得更加模块化的影响。因此,如果您在Angular Fire文档中找不到它,请转到他们的模块化web文档,其中大部分文档都适用。以下是您可以阅读更多信息的地方: https://firebase.google.com/docs/cloud-messaging/js/client

    推荐文章