Angular利用service实现自定义服务(notification)

 4405

本篇文章带大家继续angular的学习,了解一下Angular怎么利用service实现自定义服务notification),希望对大家有所帮助!


Angular利用service实现自定义服务(notification)


在之前的文章中,我们有提到:

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

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

效果图如下:


Angular利用service实现自定义服务(notification)


UI 这个可以后期调整

So,我们一步步来分解。


添加服务

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

  1. // notification.service.ts
  2.  
  3. import { Injectable } from '@angular/core';
  4. import { Observable, Subject } from 'rxjs';
  5.  
  6. // 通知状态的枚举
  7. export enum NotificationStatus {
  8.   Process = "progress",
  9.   Success = "success",
  10.   Failure = "failure",
  11.   Ended = "ended"
  12. }
  13.  
  14. @Injectable({
  15.   providedIn: 'root'
  16. })
  17. export class NotificationService {
  18.  
  19.   private notify: Subject<NotificationStatus> = new Subject();
  20.   public messageObj: any = {
  21.     primary: '',
  22.     secondary: ''
  23.   }
  24.  
  25.   // 转换成可观察体
  26.   public getNotification(): Observable<NotificationStatus> {
  27.     return this.notify.asObservable();
  28.   }
  29.  
  30.   // 进行中通知
  31.   public showProcessNotification() {
  32.     this.notify.next(NotificationStatus.Process)
  33.   }
  34.  
  35.   // 成功通知
  36.   public showSuccessNotification() {
  37.     this.notify.next(NotificationStatus.Success)
  38.   }
  39.  
  40.   // 结束通知
  41.   public showEndedNotification() {
  42.     this.notify.next(NotificationStatus.Ended)
  43.   }
  44.  
  45.   // 更改信息
  46.   public changePrimarySecondary(primary?: string, secondary?: string) {
  47.     this.messageObj.primary = primary;
  48.     this.messageObj.secondary = secondary
  49.   }
  50.  
  51.   constructor() { }
  52. }

是不是很容易理解...

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


创建组件

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

  1. notification                                          
  2. ├── notification.component.html                     // 页面骨架
  3. ├── notification.component.scss                     // 页面独有样式
  4. ├── notification.component.spec.ts                  // 测试文件
  5. └── notification.component.ts                       // javascript 文件

我们定义 notification 的骨架:

  1. <!-- notification.component.html -->
  2.  
  3. <!-- 支持手动关闭通知 -->
  4. <button (click)="closeNotification()">关闭</button>
  5. <h1>提醒的内容: {{ message }}</h1>
  6. <!-- 自定义重点通知信息 -->
  7. <p>{{ primaryMessage }}</p>
  8. <!-- 自定义次要通知信息 -->
  9. <p>{{ secondaryMessage }}</p>

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

  1. // notification.component.scss
  2.  
  3. :host {
  4.   position: fixed;
  5.   top: -100%;
  6.   right: 20px;
  7.   background-color: #999;
  8.   border: 1px solid #333;
  9.   border-radius: 10px;
  10.   width: 400px;
  11.   height: 180px;
  12.   padding: 10px;
  13.   // 注意这里的 active 的内容,在出现通知的时候才有
  14.   &.active {
  15.     top: 10px;
  16.   }
  17.   &.success {}
  18.   &.progress {}
  19.   &.failure {}
  20.   &.ended {}
  21. }

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

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

  1. // notification.component.ts
  2.  
  3. import { Component, OnInit, HostBinding, OnDestroy } from '@angular/core';
  4. // 新的知识点 rxjs
  5. import { Subscription } from 'rxjs';
  6. import {debounceTime} from 'rxjs/operators';
  7. // 引入相关的服务
  8. import { NotificationStatus, NotificationService } from 'src/app/services/notification.service';
  9.  
  10. @Component({
  11.   selector: 'app-notification',
  12.   templateUrl: './notification.component.html',
  13.   styleUrls: ['./notification.component.scss']
  14. })
  15. export class NotificationComponent implements OnInit, OnDestroy {
  16.    
  17.   // 防抖时间,只读
  18.   private readonly NOTIFICATION_DEBOUNCE_TIME_MS = 200;
  19.    
  20.   protected notificationSubscription!: Subscription;
  21.   private timer: any = null;
  22.   public message: string = ''
  23.    
  24.   // notification service 枚举信息的映射
  25.   private reflectObj: any = {
  26.     progress: "进行中",
  27.     success: "成功",
  28.     failure: "失败",
  29.     ended: "结束"
  30.   }
  31.  
  32.   @HostBinding('class') notificationCssClass = '';
  33.  
  34.   public primaryMessage!: string;
  35.   public secondaryMessage!: string;
  36.  
  37.   constructor(
  38.     private notificationService: NotificationService
  39.   ) { }
  40.  
  41.   ngOnInit(): void {
  42.     this.init()
  43.   }
  44.  
  45.   public init() {
  46.     // 添加相关的订阅信息
  47.     this.notificationSubscription = this.notificationService.getNotification()
  48.       .pipe(
  49.         debounceTime(this.NOTIFICATION_DEBOUNCE_TIME_MS)
  50.       )
  51.       .subscribe((notificationStatus: NotificationStatus) => {
  52.         if(notificationStatus) {
  53.           this.resetTimeout();
  54.           // 添加相关的样式
  55.           this.notificationCssClass = `active ${ notificationStatus }`
  56.           this.message = this.reflectObj[notificationStatus]
  57.           // 获取自定义首要信息
  58.           this.primaryMessage = this.notificationService.messageObj.primary;
  59.           // 获取自定义次要信息
  60.           this.secondaryMessage = this.notificationService.messageObj.secondary;
  61.           if(notificationStatus === NotificationStatus.Process) {
  62.             this.resetTimeout()
  63.             this.timer = setTimeout(() => {
  64.               this.resetView()
  65.             }, 1000)
  66.           } else {
  67.             this.resetTimeout();
  68.             this.timer = setTimeout(() => {
  69.               this.notificationCssClass = ''
  70.               this.resetView()
  71.             }, 2000)
  72.           }
  73.         }
  74.       })
  75.   }
  76.  
  77.   private resetView(): void {
  78.     this.message = ''
  79.   }
  80.    
  81.   // 关闭定时器
  82.   private resetTimeout(): void {
  83.     if(this.timer) {
  84.       clearTimeout(this.timer)
  85.     }
  86.   }
  87.  
  88.   // 关闭通知
  89.   public closeNotification() {
  90.     this.notificationCssClass = ''
  91.     this.resetTimeout()
  92.   }
  93.    
  94.   // 组件销毁
  95.   ngOnDestroy(): void {
  96.     this.resetTimeout();
  97.     // 取消所有的订阅消息
  98.     this.notificationSubscription.unsubscribe()
  99.   }
  100.  
  101. }

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

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

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

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

调用

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

  1. // app.component.html
  2.  
  3. <router-outlet></router-outlet>
  4. <app-notification></app-notification>

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

  1. // user-list.component.html
  2.  
  3. <button (click)="showNotification()">click show notification</button>

触发相关的代码:

  1. // user-list.component.ts
  2.  
  3. import { NotificationService } from 'src/app/services/notification.service';
  4.  
  5. // ...
  6. constructor(
  7.   private notificationService: NotificationService
  8. ) { }
  9.  
  10. // 展示通知
  11. showNotification(): void {
  12.   this.notificationService.changePrimarySecondary('主要信息 1');
  13.   this.notificationService.showProcessNotification();
  14.   setTimeout(() => {
  15.     this.notificationService.changePrimarySecondary('主要信息 2', '次要信息 2');
  16.     this.notificationService.showSuccessNotification();
  17.   }, 1000)
  18. }

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


本文网址:https://www.zztuku.com/detail-11598.html
站长图库 - Angular利用service实现自定义服务(notification)
申明:本文转载于《掘金社区》,如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐

    PS打造缝线文字效果