Angular 自定义服务 notification

简介: 比如,我们这篇文章要讲到的 notification 的实现。

image.png


一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第4天,点击查看活动详情


之前的一篇文章了解 Angular 开发的内容,我们有提到:


service 不仅可以用来处理 API 请求,还有其他的用处


比如,我们这篇文章要讲到的 notification 的实现。


效果图如下:


image.png


UI 这个可以后期调整


So,我们一步步来分解。


添加服务



我们在 app/services 中添加 notification.service.ts 服务文件(请使用命令行生成),添加相关的内容:


// notification.service.ts
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
// 通知状态的枚举
export enum NotificationStatus {
  Process = "progress",
  Success = "success",
  Failure = "failure",
  Ended = "ended"
}
@Injectable({
  providedIn: 'root'
})
export class NotificationService {
  private notify: Subject<NotificationStatus> = new Subject();
  public messageObj: any = {
    primary: '',
    secondary: ''
  }
  // 转换成可观察体
  public getNotification(): Observable<NotificationStatus> {
    return this.notify.asObservable();
  }
  // 进行中通知
  public showProcessNotification() {
    this.notify.next(NotificationStatus.Process)
  }
  // 成功通知
  public showSuccessNotification() {
    this.notify.next(NotificationStatus.Success)
  }
  // 结束通知
  public showEndedNotification() {
    this.notify.next(NotificationStatus.Ended)
  }
  // 更改信息
  public changePrimarySecondary(primary?: string, secondary?: string) {
    this.messageObj.primary = primary;
    this.messageObj.secondary = secondary
  }
  constructor() { }
}
复制代码


是不是很容易理解...


我们将 notify 变成可观察物体,之后发布各种状态的信息。


创建组件



我们在 app/components 这个存放公共组件的地方新建 notification 组件。所以你会得到下面的结构:


notification                                          
├── notification.component.html                     // 页面骨架
├── notification.component.scss                     // 页面独有样式
├── notification.component.spec.ts                  // 测试文件
└── notification.component.ts                       // javascript 文件
复制代码


我们定义 notification 的骨架:


<!-- notification.component.html -->
<!-- 支持手动关闭通知 -->
<button (click)="closeNotification()">关闭</button>
<h1>提醒的内容: {{ message }}</h1>
<!-- 自定义重点通知信息 -->
<p>{{ primaryMessage }}</p>
<!-- 自定义次要通知信息 -->
<p>{{ secondaryMessage }}</p>
复制代码


接着,我们简单修饰下骨架,添加下面的样式:


// notification.component.scss
:host {
  position: fixed;
  top: -100%;
  right: 20px;
  background-color: #999;
  border: 1px solid #333;
  border-radius: 10px;
  width: 400px;
  height: 180px;
  padding: 10px;
  // 注意这里的 active 的内容,在出现通知的时候才有
  &.active {
    top: 10px;
  }
  &.success {}
  &.progress {}
  &.failure {}
  &.ended {}
}
复制代码


success, progress, failure, ended 这四个类名对应 notification service 定义的枚举,可以按照自己的喜好添加相关的样式。


最后,我们添加行为 javascript 代码。


// notification.component.ts
import { Component, OnInit, HostBinding, OnDestroy } from '@angular/core';
// 新的知识点 rxjs
import { Subscription } from 'rxjs';
import {debounceTime} from 'rxjs/operators';
// 引入相关的服务
import { NotificationStatus, NotificationService } from 'src/app/services/notification.service';
@Component({
  selector: 'app-notification',
  templateUrl: './notification.component.html',
  styleUrls: ['./notification.component.scss']
})
export class NotificationComponent implements OnInit, OnDestroy {
  // 防抖时间,只读
  private readonly NOTIFICATION_DEBOUNCE_TIME_MS = 200;
  protected notificationSubscription!: Subscription;
  private timer: any = null;
  public message: string = ''
  // notification service 枚举信息的映射
  private reflectObj: any = {
    progress: "进行中",
    success: "成功",
    failure: "失败",
    ended: "结束"
  }
  @HostBinding('class') notificationCssClass = '';
  public primaryMessage!: string;
  public secondaryMessage!: string;
  constructor(
    private notificationService: NotificationService
  ) { }
  ngOnInit(): void {
    this.init()
  }
  public init() {
    // 添加相关的订阅信息
    this.notificationSubscription = this.notificationService.getNotification()
      .pipe(
        debounceTime(this.NOTIFICATION_DEBOUNCE_TIME_MS)
      )
      .subscribe((notificationStatus: NotificationStatus) => {
        if(notificationStatus) {
          this.resetTimeout();
          // 添加相关的样式
          this.notificationCssClass = `active ${ notificationStatus }`
          this.message = this.reflectObj[notificationStatus]
          // 获取自定义首要信息
          this.primaryMessage = this.notificationService.messageObj.primary;
          // 获取自定义次要信息
          this.secondaryMessage = this.notificationService.messageObj.secondary;
          if(notificationStatus === NotificationStatus.Process) {
            this.resetTimeout()
            this.timer = setTimeout(() => {
              this.resetView()
            }, 1000)
          } else {
            this.resetTimeout();
            this.timer = setTimeout(() => {
              this.notificationCssClass = ''
              this.resetView()
            }, 2000)
          }
        }
      })
  }
  private resetView(): void {
    this.message = ''
  }
  // 关闭定时器
  private resetTimeout(): void {
    if(this.timer) {
      clearTimeout(this.timer)
    }
  }
  // 关闭通知
  public closeNotification() {
    this.notificationCssClass = ''
    this.resetTimeout()
  }
  // 组件销毁
  ngOnDestroy(): void {
    this.resetTimeout();
    // 取消所有的订阅消息
    this.notificationSubscription.unsubscribe()
  }
}
复制代码


在这里,我们引入了 rxjs 这个知识点,RxJS 是使用 Observables 的响应式编程的库,它使编写异步或基于回调的代码更容易。这是一个很棒的库,接下来的很多文章你会接触到它更多的内容。


这里我们使用了 debounce 防抖函数,函数防抖,就是指触发事件后,在 n 秒后只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数的执行时间。简单来说:当一个动作连续触发,只执行最后一次。


ps: throttle 节流函数:限制一个函数在一定时间内只能执行一次


在面试的时候,面试官很喜欢问...


调用



因为这个一个全局的服务,我们在 app.component.html 中调用此组件:


// app.component.html
<router-outlet></router-outlet>
<app-notification></app-notification>
复制代码


为了方便演示,我们在 user-list.component.html 中添加按钮,方便触发演示:


// user-list.component.html
<button (click)="showNotification()">click show notification</button>
复制代码


触发相关的代码:


// user-list.component.ts
import { NotificationService } from 'src/app/services/notification.service';
// ...
constructor(
  private notificationService: NotificationService
) { }
// 展示通知
showNotification(): void {
  this.notificationService.changePrimarySecondary('主要信息 1');
  this.notificationService.showProcessNotification();
  setTimeout(() => {
    this.notificationService.changePrimarySecondary('主要信息 2', '次要信息 2');
    this.notificationService.showSuccessNotification();
  }, 1000)
}
复制代码


至此,大功告成,我们成功模拟了 notification 的功能。相关的服务组件我们可以按照实际的需求进行修改,满足业务需求自定义。如果我们是开发内部使用的系统的话,建议使用成熟的 UI 库,它们已经帮我们封装好各种组件和服务,大量节省我们的开发时间。



相关文章
|
2月前
|
开发者 iOS开发 C#
Uno Platform 入门超详细指南:从零开始教你打造兼容 Web、Windows、iOS 和 Android 的跨平台应用,轻松掌握 XAML 与 C# 开发技巧,快速上手示例代码助你迈出第一步
【8月更文挑战第31天】Uno Platform 是一个基于 Microsoft .NET 的开源框架,支持使用 C# 和 XAML 构建跨平台应用,适用于 Web(WebAssembly)、Windows、Linux、macOS、iOS 和 Android。它允许开发者共享几乎全部的业务逻辑和 UI 代码,同时保持原生性能。选择 Uno Platform 可以统一开发体验,减少代码重复,降低开发成本。安装时需先配置好 Visual Studio 或 Visual Studio for Mac,并通过 NuGet 或官网下载工具包。
59 0
|
2月前
|
前端开发 开发者 C#
深度解析 Uno Platform 中的 MVVM 模式:从理论到实践的全方位指南,助你轻松掌握通过 C# 与 XAML 构建高效可维护的跨平台应用秘籍
【8月更文挑战第31天】本文详细介绍如何在优秀的跨平台 UI 框架 Uno Platform 中实施 MVVM(Model-View-ViewModel)模式,通过一个简单的待办事项列表应用演示其实现过程。MVVM 模式有助于分离视图层与业务逻辑层,提升代码组织性、易测性和可维护性。Uno Platform 的数据绑定机制使视图与模型间的同步变得高效简便。文章通过构造 `TodoListViewModel` 类及其相关视图,展示了如何解耦视图与模型,实现动态数据绑定及命令处理,从而提高代码质量和开发效率。通过这一模式,开发者能更轻松地构建复杂的跨平台应用。
28 0
|
2月前
|
前端开发 UED 开发者
无障碍设计的魔法:JSF让每个用户都能畅游数字世界!
【8月更文挑战第31天】本文介绍如何使用JavaServer Faces (JSF)构建无障碍Web应用,确保所有用户都能访问和使用。文章通过实际代码示例展示了如何利用ARIA属性增强组件、实现键盘导航、提供文本替代以及使用语义化标签等技术。无障碍设计不仅是道德责任,也是提升用户体验的关键。通过这些方法,JSF可以帮助开发者创建更加公平和包容的应用。
27 0
|
2月前
|
JavaScript 前端开发
如何在 Angular 中为响应式表单创建自定义验证器
如何在 Angular 中为响应式表单创建自定义验证器
16 0
|
2月前
|
JavaScript
如何在自定义 Angular 指令中使用 @HostBinding 和 @HostListener
如何在自定义 Angular 指令中使用 @HostBinding 和 @HostListener
29 0
|
2月前
在Angular中创建自定义管道
在Angular中创建自定义管道
12 0
|
2月前
|
JavaScript 安全
如何在 Angular Material 中使用自定义 SVG 图标
如何在 Angular Material 中使用自定义 SVG 图标
52 0
|
2月前
|
JavaScript
如何使用 ControlValueAccessor 在 Angular 中创建自定义表单控件
如何使用 ControlValueAccessor 在 Angular 中创建自定义表单控件
14 0
|
3月前
|
设计模式 JavaScript 测试技术
Angular服务与依赖注入机制详解
【7月更文挑战第17天】Angular的服务与依赖注入机制为构建模块化、可维护和可扩展的应用程序提供了强大的支持。通过合理定义和使用服务,以及利用依赖注入来管理依赖关系,我们可以编写出更加清晰、可维护和可测试的代码。希望本文能帮助你更好地理解和应用Angular的服务与依赖注入机制。
|
3月前
|
前端开发 JavaScript
前端框架与库 - Angular基础:组件、模板、服务
【7月更文挑战第16天】Angular,谷歌维护的前端框架,专注构建动态Web应用。组件是核心,包含行为逻辑的类、定义视图的模板和样式。模板语法含插值、属性和事件绑定。服务提供业务逻辑,依赖注入实现共享。常见问题涉及组件通信、性能和服务注入。优化通信、性能并正确管理服务范围,能提升应用效率和质量。学习组件、模板和服务基础,打造高效Angular应用。
59 1
下一篇
无影云桌面