发布于 2026-01-06 0 阅读
0

如何向 Angular 应用添加应用内通知

如何向 Angular 应用添加应用内通知

太长不看

本文将介绍如何在 Angular 应用中添加应用内通知中心,并为您带来一些令人愉悦的发现🙃

其中一张截图中提到了我最喜欢的电影之一。如果你能猜出是哪部电影,并在评论区留下你的答案,我会在下一篇文章中以某种方式感谢你。🤓

截屏

既然你满意了,我们就可以开始教程了。

我们提供多种通知功能,这些通知可能对您的使用场景很有帮助或必不可少。

以下是一些您可能比较熟悉的通知(沟通)渠道:

  • 应用内
  • 短信
  • 电子邮件
  • 聊天工具(Discord、Slack、MS Teams、WhatsApp、Telegram)

然而,我们只会享用这美味馅饼的五分之一——应用内通知。这种沟通渠道允许您在应用内与用户互动。

假设你过去十年没有与世隔绝,那么让我们来看一个以 Instagram 这样的社交媒体应用为例,了解一下应用内基于事件的通知工作流程:

图像

  1. 用户打开 Instagram 应用,滚动浏览动态,查看其他用户发布的照片​​和视频。
  2. 用户将照片或视频发布到自己的 Instagram 个人主页。
  3. 另一位用户看到了这条帖子并点赞了。
  4. Instagram 应用会检测到点赞事件,并向发布该内容的用户发送通知。
  5. 通知会出现在用户的屏幕上,告知他们有其他用户点赞了他们的帖子。
  6. 用户可以选择忽略通知,也可以点击通知打开应用查看点赞其帖子的用户。
  7. 如果用户点击通知并打开应用,他们可以看到点赞自己帖子的用户的个人资料,并通过点赞他们的帖子或关注他们的帐户与他们互动。

截屏

既然我们已经知道要做什么,那就让我们把应用内通知集成到我们的应用中吧。

嗯……这不是先有鸡还是先有蛋的问题;我们首先需要有“鸡”——我们的应用程序。

我最近开始尝试使用 Angular,并且已经非常喜欢这个框架,但我不会试图说服你加入它的阵营。

欢迎访问已部署的版本:https://in-app-notification-with-angular.vercel.app/

或者克隆这个仓库

它应该长这样:

截屏

创建一个 Angular 应用

前提条件:(确保你没有脱发的必要条件)

开始之前,请确保您的系统已安装以下软件:

  • Node.js
  • NPM(Node 包管理器)
  • Angular CLI(命令行界面)
  • Angular 版本 > 0.15.0

如果仍需安装这些工具,您可以从其官方网站下载并安装。

步骤 1:创建一个新的 Angular 应用

要创建一个新的 Angular 应用,请打开终端或命令提示符并运行以下命令:

ng new my-app
Enter fullscreen mode Exit fullscreen mode

这里my-app是你的新 Angular 应用的名称。这条命令会创建一个新的 Angular 应用,其中包含基本文件结构并安装所有必要的依赖项。

步骤 2:启动开发服务器

运行以下命令导航到应用程序目录:

cd my-app
Enter fullscreen mode Exit fullscreen mode

进入应用目录后,您可以通过运行以下命令启动开发服务器:

ng serve
Enter fullscreen mode Exit fullscreen mode

此命令将启动开发服务器并在默认浏览器中启动您的应用程序。您可以通过导航至http://localhost:4200/. 来访问您的应用程序。

截屏

步骤 3:修改应用程序

现在您的应用已经启动并运行,您可以开始根据自己的需求对其进行修改。您可以通过编辑目录中的文件来修改应用src

  • index.html此文件是您的应用程序的主要入口点。
  • app.component.ts此文件包含您的应用程序的主要组件。
  • app.component.html此文件包含应用程序组件的 HTML 模板。
  • app.component.css此文件包含应用程序组件的 CSS 样式。
  • app.component.spec.ts:此文件包含应用程序根目录的单元测试。

您可以修改这些文件,为您的应用程序添加新组件、更改布局、添加测试或新功能。

注册 Novu

我们将使用现成的解决方案来实现通知功能,因为我们比较懒,总是想在生活中走捷径。

(那些千禧一代……)

如果你以前尝试过自己搭建通知系统,那么在阅读本文之前,你很快就会爱上我。

我们将使用 Novu,因为它是一个开源的通知基础设施,使我们能够触发基于事件的通知工作流程。

第一步:注册

点击此链接

截屏

步骤 2:创建工作流程

您可以按照入门指南操作,或者前往通知模板页面创建您的模板(工作流程)。

截屏

添加通知中心

步骤 1:安装

在终端中,导航到 Angular 应用程序的根目录。

cd my-app
Enter fullscreen mode Exit fullscreen mode

运行以下命令生成新组件:

npm install @novu/notification-center-angular

or

yarn add @novu/notification-center-angular
Enter fullscreen mode Exit fullscreen mode

步骤 2:添加 Novu 模块

现在,导航到app.module.ts文件(my-app/src/app/app.module.ts)

// my-app/src/app/app.module.ts
****
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
Enter fullscreen mode Exit fullscreen mode

CUSTOM_ELEMENTS_SCHEMA……导入'@angular/core'

// my-app/src/app/app.module.ts

import { CUSTOM_ELEMENTS_SCHEMA, NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
Enter fullscreen mode Exit fullscreen mode

添加 Novu 的通知中心模块

// my-app/src/app/app.module.ts

import { CUSTOM_ELEMENTS_SCHEMA, NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { NotificationCenterModule } from '@novu/notification-center-angular';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    NotificationCenterModule
  ],
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
Enter fullscreen mode Exit fullscreen mode

步骤 3:配置应用程序环境

使用 Angular CLI,首先运行 此处显示的generate environments 命令
 来创建 src/environments/
 目录并配置项目以使用这些文件。

ng generate environments
Enter fullscreen mode Exit fullscreen mode

导航至my-app/src/environments/environment.ts并添加以下变量:subscriberIdapplicationIdentifier

export const environment = {
    production: false,
    subscriberId: "",
    applicationIdentifier: ""
};
Enter fullscreen mode Exit fullscreen mode

我们的通知中心需要这些变量GET才能向 Novu 的 API 发出请求,从而将通知实际推送到信息流中。

现在我们需要添加这些变量:

Application Identifier您可以在这里找到:https://web.novu.co/settings(Novu 的设置部分)

截屏

subscriberId您可以在这里找到:https://web.novu.co/subscribers(Novu 的订阅用户专区)

截屏

现在把它添加到你的my-app/src/environments/environment.ts文件中

export const environment = {
    production: true,
    subscriberId: "<REPLACE_WITH_USER_UNIQUE_IDENTIFIER>",
    applicationIdentifier: "<REPLACE_WITH_APP_ID_FROM_ADMIN_PANEL>"
};
Enter fullscreen mode Exit fullscreen mode

并写入my-app/src/environments/environment.development.ts文件

export const environment = {
    production: false,
    subscriberId: "<REPLACE_WITH_USER_UNIQUE_IDENTIFIER>",
    applicationIdentifier: "<REPLACE_WITH_APP_ID_FROM_ADMIN_PANEL>"
};
Enter fullscreen mode Exit fullscreen mode

我们去my-app/src/app/app.component.ts文件区看看。

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'my-app';
}
Enter fullscreen mode Exit fullscreen mode

app.component.ts文件是 Angular 应用程序的关键部分,因为它定义了根组件,并为应用程序的其余功能提供了基础。

现在,我们将导入这些environment变量,以便它们可以在通知中心的属性中访问app.component.htmlstyles有很多属性,但您可以稍后了解它们)。

import { Component } from '@angular/core';
import { environment } from '../environments/environment';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'my-app';

  subscriberId = environment.subscriberId;
  applicationIdentifier = environment.applicationIdentifier;

styles = {
    bellButton: {
      root: {
        svg: {
          color: 'white',
          width: '45px',
          height: '40px',
          fill: 'white',
        },
      },
      dot: {
        rect: {
          fill: 'rgb(221, 0, 49)',
          strokeWidth: '0.2',
          stroke: 'white',
          width: '3.5px',
          height: '3.5px',
        },
        left: '40%',
      },
    },
    header: {
      root: {
        backgroundColor: '',
        '&:hover': { backgroundColor: '' },
        '.some_class': { color: '' },
      },
    },
    layout: {
      root: {
        backgroundColor: '',
      },
    },
    popover: {
      arrow: {
        backgroundColor: '',
        border: '',
      },
    },
  };

  sessionLoaded = (data: unknown) => {
    console.log('loaded', { data });
  };
}
Enter fullscreen mode Exit fullscreen mode

您可能会看到一些错误,[localhost:4200](http://localhost:4200)我们会立即修复!

截屏

这是因为 Angular 组件是作为原始 React 组件的包装器生成的。这种方法很巧妙,因为它让 Novu 的工程师能够专注于以 React 的方式创建和开发组件。此外,许多其他框架仍然可以使用这种包装方式创建的组件。

我们需要将其添加@types/react为开发依赖项,Angular 组件才能正常工作。

打开终端,导航到应用程序根目录,然后输入以下命令:

npm i @types/react

or

yarn add @types/react
Enter fullscreen mode Exit fullscreen mode

现在前往my-app/tsconfig.json文件

/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noImplicitOverride": true,
    "noPropertyAccessFromIndexSignature": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "ES2022",
    "module": "ES2022",
    "useDefineForClassFields": false,
    "lib": [
      "ES2022",
      "dom"
    ]
  },
  "angularCompilerOptions": {
    "enableI18nLegacyMessageIdFormat": false,
    "strictInjectionParameters": true,
    "strictInputAccessModifiers": true,
    "strictTemplates": true
  }
}
Enter fullscreen mode Exit fullscreen mode

我们将向数组"allowSyntheticDefaultImports": true中添加compilerOptions元素。

/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
  "compileOnSave": false,
  "compilerOptions": {
    "allowSyntheticDefaultImports": true, 
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noImplicitOverride": true,
    "noPropertyAccessFromIndexSignature": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "ES2022",
    "module": "ES2022",
    "useDefineForClassFields": false,
    "lib": [
      "ES2022",
      "dom"
    ]
  },
  "angularCompilerOptions": {
    "enableI18nLegacyMessageIdFormat": false,
    "strictInjectionParameters": true,
    "strictInputAccessModifiers": true,
    "strictTemplates": true
  }
}
Enter fullscreen mode Exit fullscreen mode

要查看错误是否已解决,您可能需要进入运行该应用程序的终端,然后再次运行该应用程序,以使compilerOptions更改生效。

步骤 4:添加通知中心组件

打开my-app/src/app/app.component.html文件。

此文件包含 CSS 代码和 HTML 代码 - 理想情况下,您应该将 CSS 代码单独放在一个my-app/src/app/app.component.css文件中,但这并非强制性的。

我们将把通知中心添加到 .toolbar div 元素中。

将以下内容粘贴到您的app.component.html文件中:

    <div id="bell-icon">
    <notification-center-component
      [subscriberId]="subscriberId"
      [applicationIdentifier]="applicationIdentifier"
      [sessionLoaded]="sessionLoaded"
      [styles]="styles"
    ></notification-center-component>
  </div>
Enter fullscreen mode Exit fullscreen mode

该div元素应该看起来像这样:

<!-- Toolbar -->
<div class="toolbar" role="banner">
  <img
    width="40"
    alt="Angular Logo"
    src="<TOO LONG FOR DEV.TO MARKDOWN TO PROCESS>"
  />
  <span>Welcome</span>
    <div class="spacer"></div>
    <div id="bell-icon">
    <notification-center-component
      [subscriberId]="subscriberId"
      [applicationIdentifier]="applicationIdentifier"
      [sessionLoaded]="sessionLoaded"
      [styles]="styles"
    ></notification-center-component>
      </div>
    <a aria-label="Angular on twitter" target="_blank" rel="noopener" href="https://twitter.com/angular" title="Twitter">
      <svg id="twitter-logo" height="24" data-name="Logo" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 400">
        <rect width="400" height="400" fill="none"/>
        <path d="<TOO LONG FOR DEV.TO MARKDOWN TO PROCESS>" fill="#fff"/>
      </svg>
    </a>
    <a aria-label="Angular on YouTube" target="_blank" rel="noopener" href="https://youtube.com/angular" title="YouTube">
      <svg id="youtube-logo" height="24" width="24" data-name="Logo" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="#fff">
        <path d="M0 0h24v24H0V0z" fill="none"/>
        <path d="<TOO LONG FOR DEV.TO MARKDOWN TO PROCESS>"/>
      </svg>
    </a>
</div>
Enter fullscreen mode Exit fullscreen mode

<style>标签中,我们还要给我们的图标添加一些边距#bell-icon,以便它与其他图标放在一起看起来更美观。

.toolbar #bell-icon {
    height: '';
    margin: 0 16px;
}
Enter fullscreen mode Exit fullscreen mode

现在你应该能在应用的工具栏部分看到铃铛图标(通知中心)。

截屏

截屏

测试通知中心

如果失败了,那会非常尴尬,但不要因此气馁,再仔细检查一遍之前的步骤,确保没有遗漏或跳过任何内容。

现在让我们测试一下通知工作流程(模板):

截屏

您应该会看到一个红点,表示您已收到通知。

截屏

截屏

就这样!

这就是我们在本教程开始时想要达到的目标。
如果你已经按照步骤操作到这里,并且你的应用运行正常,那就好好犒劳一下自己吧!恭喜你,你做得很好!

接下来,我将分享许多关于 Angular 的教程和应用程序,敬请期待。

下次再见,
皮尔斯曼

文章来源:https://dev.to/novu/how-to-add-in-app-notifications-to-your-angular-app-2dp3