我有一个Angular 15的项目,我想增加FCM到它.

enter image description here

  1. 我安装了@ANGLING/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 {}

如何在@ANGLING/FIRE版本^7.5.0中请求权限并获取FCM令牌??

我找到了许多使用这种语法的教程和文章,但它在版本7中不是有效的语法,在@Angel/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);
      }
    );
  }
}

推荐答案

要解决缺乏关于更新版本的@Angel/Fire的文档的问题,关键是要记住这一点:

新版本完全是模块化的,并试图使其更容易在Bundle 包中包含您想要和需要的内容.因此,如果您需要的话,您可以导入getToken function,而不是属于您要注入的服务的一个实例的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')
    );
  }
}

令我沮丧的是,在某些方面,角火的文档仍然缺乏最新版本.但你会开始注意到他们追求的一种模式,它受到非Angular Web库变得更加模块化的影响.因此,如果你在Angular 之火的文档中找不到它,可以直接访问他们的模块化Web文档,这些文档中的大多数都适用.这里是你可以阅读更多关于消息的地方:https://firebase.google.com/docs/cloud-messaging/js/client

Angular相关问答推荐

Angular 动画—淡出适用于DIV,不完全适用于子组件

Angular路由不响应子路由的子路由

在Angular 多选下拉菜单中实现CDK拖放排序的问题

图像未显示在视图屏幕上-Angular 投影

NG-BOOTSTRAPP SCROLLESPY没有高度就不能工作?

Primeng:安装ANGLE 16.2.0版本

列表和映射的SCSS语法

Angular 16模块中未使用的组件是否从Bundle 包中删除(树摇动)?

如何在独立应用程序中全局禁用基于媒体查询的Angular 动画?

除非将 signal.set 作为间隔的一部分调用,否则Angular 信号效果不会执行

Observable转换为Observable

Angular 在关闭另一个对话框后打开另一个对话框的最佳做法是什么?

Angular 获取视频持续时间并存储在外部变量中

TypeError:this.restoreDialogRef.afterClosed 不是函数

当访问令牌在 MSAL for Angular 中过期时如何重定向用户?

将数组传递给 URLSearchParams,同时使用 http 调用获取请求

全局异常处理

如何在 Angular 2 中使用 protractor ?

将查询参数附加到 URL

Angular2:如果 img src 无效,则显示占位符图像