我们在
app/services
中添加
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
的骨架:
<button (click)="closeNotification()">关闭</button>
<h1>提醒的内容: {{ message }}</h1>
<p>{{ primaryMessage }}</p>
<p>{{ secondaryMessage }}</p>
接着,我们简单修饰下骨架,添加下面的样式:
:host {
position: fixed;
top: -100%;
right: 20px;
background-color: #999;
border: 1px solid #333;
border-radius: 10px;
width: 400px;
height: 180px;
padding: 10px;
&.active {
top: 10px;
&.success {}
&.progress {}
&.failure {}
&.ended {}
success, progress, failure, ended
这四个类名对应 notification service 定义的枚举,可以按照自己的喜好添加相关的样式。
最后,我们添加行为 javascript
代码。
import { Component, OnInit, HostBinding, OnDestroy } from '@angular/core';
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 = ''
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>
触发相关的代码:
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 库,它们已经帮我们封装好各种组件和服务,大量节省我们的开发时间。
【完】✅