Angular learning chat notification (custom service)
This article will take you to continue learning angular and briefly understand the custom service notification in angular. 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 the notification.service.ts service file in app/services (please use the command Line generation), 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 statuses Information.
Create component
We create a new notification component in app/components where public components are stored. 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.
Finally, we add the behavioral 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.
Here we use the 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:
throttleThrottle function: Limit a function to be executed only once within a certain period of time.
During the interview, the interviewer likes to ask...
Calling
Because this is a global service, we are Call this component in app.component.html:
// app.component.html <router-outlet></router-outlet> <app-notification></app-notification>
In order to facilitate the demonstration, we add a button in user-list.component.html to facilitate the triggering of 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.
【End】✅
For more programming-related knowledge, please visit: Programming Teaching! !
The above is the detailed content of Angular learning chat notification (custom service). For more information, please follow other related articles on the PHP Chinese website!
JavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AMJavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.
JavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AMThe main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.
Understanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AMUnderstanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.
Python vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AMPython is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.
Python vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AMPython and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


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

SublimeText3 Chinese version
Chinese version, very easy to use

Dreamweaver Mac version
Visual web development tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Mac version
God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.







