Angular利用service实现自定义服务(notification)
时间:2022-04-17 [网络编程]作者:fabuyuan 浏览:10 次
在之前的文章中,我们有提到:
service 不仅可以用来处理 API 请求,还有其他的用处
比如,我们这篇文章要讲到的 notification
的实现。【相关教程推荐:《angular教程》】
效果图如下:
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 库,它们已经帮我们封装好各种组件和服务,大量节省我们的开发时间。
更多编程相关知识,请访问:编程入门!!
以上就是Angular利用service实现自定义服务(notification)的详细内容,更多请关注站长家园其它相关文章!
本文标签: Angularservice自定义服务notification
转载请注明来源:Angular利用service实现自定义服务(notification)
本文永久链接地址:https://www.adminjie.com/post/11258.html
免责声明:
本站所发布的一切资源仅限用于学习和研究目的;不得将上述内容用于商业或者非法用途,否则,一切后果请用户自负。本站信息来自网络,版权争议与本站无关。您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。如果您喜欢该程序,请支持正版软件,购买注册,得到更好的正版服务。
附:
二○○二年一月一日《计算机软件保护条例》第十七条规定:为了学习和研究软件内含的设计思想和原理,通过安装、显示、传输或者存储软件等方式使用软件的,可以不经软件著作权人许可,不向其支付报酬!鉴于此,也希望大家按此说明研究软件!
版权声明:
一、本站致力于为软件爱好者提供国内外软件开发技术和软件共享,着力为用户提供优资资源。
二、本站提供的部分源码下载文件为网络共享资源,请于下载后的24小时内删除。如需体验更多乐趣,还请支持正版。
三、我站提供用户下载的所有内容均转自互联网。如有内容侵犯您的版权或其他利益的,若有侵犯你的权益请:提交版权证明文件到邮箱 2225329873#qq.com(#换为@) 站长会进行审查之后,情况属实的会在三个工作日内为您删除。
更多精彩内容
- VUE中V-IF条件判断改变元素的样式操作
- Discuz如何解决安装时报错run_sql_error
- 低版本VS项目在VS2019无法正常编译的问题
- PHP+Redis链表解决高并发下商品超卖问题(实现原理及步骤)
- Oracle数据库的实例/表空间/用户/表之间关系简单讲解
- RSA2是啥?PHP-RSA2签名验证怎么实现?
- 华为dubal20是什么型号
- ana an00华为是什么型号
- html5的标题标记一共有几个等级
- 电脑显示信号线无连接是什么意思
- app是什么应用程序的简称
- html5中onclick是什么意思
- 小程序大小超限除了分包还能怎么做?如何避免和解决大小限制?
- angular与bootstrap的区别是什么
- vivov1818a是什么手机型号

- 最新文章
-
-
oracle怎么实现主键自增
方法:1、用“createsequence序列名minvalue...”创建序列;2、利用“createorreplacetrigger触发器名...
-
JavaScript字符串常见基础方法精讲
本篇文章给大家带来了关于javascript的相关知识,其中主要介绍了关于字符串的相关知识,其中主要介绍了常用的基础方法以及特殊字符、emoji内部表示方式等内...
-
一起聊聊Excel逆向查询问题
本篇文章给大家带来了关于excel的相关知识,其中主要介绍了关于逆向查询的相关问题,就是关键字在数据表的右侧,而要得到内容在数据表的左侧,下面一起来看一下,希望...
-
2022年开发人员不可错过的 Web 平台的新动态
5月11-12日,谷歌举办了2022GoogleI/O全球开发者大会。在大会上,JakeArchibald和UnaKravet向我们介绍了...
-
linux中cp命令怎么设置不提示
linux中设置cp命令不提示方法:1、修改“~/.bashrc”文件,禁用cp命令的alias,只需将“aliascp='cp-i'”内容注释掉即可;2、...
-
- 热门文章
-
-
VUE中V-IF条件判断改变元素的样式操作
这篇文章主要介绍了VUE中V-IF条件判断改变元素的样式操作,具有很好的参考价值,希望对大家有所帮助。一起跟随想过来看看吧...
-
Discuz如何解决安装时报错run_sql_error
问题环境VMware虚拟机Centos7.3PHP7.0MySQL8.0NGINX1.14Discuz3.4问题还原本地环境为PHP5.6+MySQL5.6在安...
-
低版本VS项目在VS2019无法正常编译的问题
低版本VS项目在VS2019无法正常编译的问题这里指的编译并不准确,只是为了方便说明。后有(未安装),201?...
-
PHP+Redis链表解决高并发下商品超卖问题(实现原理及步骤)
实现原理使用redis链表来做,因为pop操作是原子的,即使有很多用户同时到达,也是依次执行,推荐使用。实现步骤第一步,先将商品库存入队列/**.trigge...
-
Oracle数据库的实例/表空间/用户/表之间关系简单讲解
完整的Oracle数据库通常由两部分组成:Oracle数据库和数据库实例。Oracle是一种数据库管理系统,是一种关系型的数据库管理系统。我们用这些高级权限账号...
-