• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • dedecms
  • ecshop
  • z-blog
  • UcHome
  • UCenter
  • drupal
  • WordPress
  • 帝国cms
  • phpcms
  • 动易cms
  • phpwind
  • discuz
  • 科汛cms
  • 风讯cms
  • 建站教程
  • 运营技巧
您的位置:首页 > CMS教程 >建站教程 > Angular利用service实现自定义服务(notification)

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

作者:站长图库 字体:[增加 减小] 来源:互联网 时间:2022-04-29

站长图库向大家介绍了Angular,service自定义服务,notification等相关知识,希望对您有所帮助

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


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


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

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

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

效果图如下:


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


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';// 新的知识点 rxjsimport { 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 库,它们已经帮我们封装好各种组件和服务,大量节省我们的开发时间。


分享到:QQ空间新浪微博腾讯微博微信百度贴吧QQ好友复制网址打印

您可能想查找下面的文章:

  • 什么是依赖注入?在Angular中怎么实现?
  • Angular CLI发布路径的配置项浅析
  • 浅析Angular中HttpClientModule模块有什么用?怎么用?
  • 浅谈Angular中elem.scope()、elem.isolateScope和$compile(elem)(scope)中scope的区别
  • 详解Angular中的Observable(可观察对象)
  • 浅析Angular+rxjs怎么实现拖拽功能?
  • 聊聊在Angular项目中怎么实现权限控制?
  • Angular中怎么自定义视频播放器
  • 详解Angular中的NgModule(模块)
  • Angular学习之以Tooltip为例了解自定义指令

相关文章

  • 2022-04-29简单聊聊Redis中GETBIT和SETBIT
  • 2022-04-29Photoshop制作2013花纹装饰艺术字
  • 2022-04-29Photoshop详细解析斜面浮雕和等高线原理
  • 2022-04-29Uniapp中怎么使用scrpll-view组件实现下拉刷新
  • 2022-04-29Photoshop设计国外木纹风格的网页模板
  • 2022-04-29纯CSS巧妙的实现带圆角的三角形
  • 2022-04-29社交网站内容对SEO的价值
  • 2022-04-29如何优化css expression性能
  • 2022-04-29Photoshop制作冬季雪花字教程
  • 2022-04-29解决JavaScript中数组排序sort不发生改变

文章分类

  • dedecms
  • ecshop
  • z-blog
  • UcHome
  • UCenter
  • drupal
  • WordPress
  • 帝国cms
  • phpcms
  • 动易cms
  • phpwind
  • discuz
  • 科汛cms
  • 风讯cms
  • 建站教程
  • 运营技巧

最近更新的内容

    • 浅析微信小程序和web之间的交互(代码分享)
    • 聊聊从H5页面跳转到小程序的几种实现方案
    • 宝塔面板7.X高级破解版代码
    • 介绍thinkphp5框架中的hook机制
    • 教你一招搞定mysql中的sql_mode设置
    • PhotoShop打造抽象几何时尚美女海报制作教程
    • 宝塔linux管理助手安装完后显示IP为内网IP怎么办
    • Photoshop设计炫彩效果的光环标志教程
    • Wordpress Ripro美化版演示导入说明
    • Photoshop制作逼真的镶嵌钻石艺术字

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有