This article will take you to continue learning angular and learn how Angular uses service to implement custom services (notification). I hope it will be helpful to everyone!
In the previous article, we mentioned:
service can not only be used to process API requests, but also has other uses
For example, the implementation of notification
we are going to talk about in this article. [Related tutorial recommendations: "angular tutorial"]
The rendering is as follows:
UI This can be adjusted later
So, let’s break it down step by step.
Add service
We add notification.service.ts
in app/services
Service file (please use the command line to generate), add relevant content:
// 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() { } }
Is it easy to understand...
We will notify
into an observable object , and then publish various status information.
Create component
We create a new notification## in
app/components where public components are stored. # components. So you will get the following structure:
notification ├── notification.component.html // 页面骨架 ├── notification.component.scss // 页面独有样式 ├── notification.component.spec.ts // 测试文件 └── notification.component.ts // javascript 文件We define the skeleton of
notification:
<!-- notification.component.html --> <!-- 支持手动关闭通知 --> <button (click)="closeNotification()">关闭</button> <h1 id="提醒的内容-nbsp-nbsp-message-nbsp">提醒的内容: {{ message }}</h1> <!-- 自定义重点通知信息 --> <p>{{ primaryMessage }}</p> <!-- 自定义次要通知信息 --> <p>{{ secondaryMessage }}</p>Then, we simply modify the skeleton and add the following style:
// 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 These four class names correspond to the enumeration defined by the notification service. You can add related styles according to your own preferences.
javascript code.
// 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() } }Here, we introduce the knowledge point of
rxjs, RxJS is a reactive programming library using Observables, which enables writing Asynchronous or callback based code is easier. This is a great library, and you’ll learn more about it in the next few articles.
debounce anti-shake function,
function anti-shake means that after the event is triggered, it can only be executed once after n seconds. If it is triggered again within n seconds event, the execution time of the function will be recalculated. To put it simply: when an action is triggered continuously, only the last time is executed.
ps:During the interview, the interviewer likes to ask...throttle
Throttle function:
Limit a function to be executed only once within a certain period of time.
call
Because this one For global services, we call this component inapp.component.html:
// app.component.html <router-outlet></router-outlet> <app-notification></app-notification>For the convenience of demonstration, we add it in
user-list.component.html Button to facilitate triggering the demonstration:
// user-list.component.html <button (click)="showNotification()">click show notification</button>Trigger related code:
// 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) }At this point, we are done, we have successfully simulated the function of
notification. We can modify related service components according to actual needs and customize them to meet business needs. If we are developing a system for internal use, it is recommended to use mature UI libraries. They have already helped us encapsulate various components and services, saving us a lot of development time.
Introduction to Programming! !
The above is the detailed content of Angular uses service to implement custom services (notification). For more information, please follow other related articles on the PHP Chinese website!

本篇文章继续Angular的学习,带大家了解一下Angular中的元数据和装饰器,简单了解一下他们的用法,希望对大家有所帮助!

本篇文章带大家深入了解一下angular的状态管理器NgRx,介绍一下NgRx的使用方法,希望对大家有所帮助!

angular中怎么使用monaco-editor?下面本篇文章记录下最近的一次业务中用到的 monaco-editor 在 angular 中的使用,希望对大家有所帮助!

本篇文章给大家分享一个Angular实战,了解一下angualr 结合 ng-zorro 如何快速开发一个后台系统,希望对大家有所帮助!

Angular项目过大,怎么合理拆分它?下面本篇文章给大家介绍一下合理拆分Angular项目的方法,希望对大家有所帮助!

怎么自定义angular-datetime-picker格式?下面本篇文章聊聊自定义格式的方法,希望对大家有所帮助!

本篇文章带大家了解一下Angular中的独立组件,看看怎么在Angular中创建一个独立组件,怎么在独立组件中导入已有的模块,希望对大家有所帮助!

Angular Route中怎么提前获取数据?下面本篇文章给大家介绍一下从 Angular Route 中提前获取数据的方法,希望对大家有所帮助!


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version
Visual web development tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
