Angular uses service to implement custom services (notification)

青灯夜游
Release: 2022-04-29 21:12:04
forward
2470 people have browsed it

This article will take you to continue learningangularand learn how Angular uses service to implement custom services (notification). I hope it will be helpful to everyone!

Angular uses service to implement custom services (notification)

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 ofnotificationwe are going to talk about in this article. [Related tutorial recommendations: "angular tutorial"]

The rendering is as follows:

Angular uses service to implement custom services (notification)

UI This can be adjusted later

So, let’s break it down step by step.

Add service

We addnotification.service.tsinapp/servicesService 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 = new Subject(); public messageObj: any = { primary: '', secondary: '' } // 转换成可观察体 public getNotification(): Observable { 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() { } }
Copy after login

Is it easy to understand...

We willnotifyinto an observable object , and then publish various status information.

Create component

We create a newnotification## inapp/componentswhere 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 文件
Copy after login

We define the skeleton of

notification:

   

提醒的内容: {{ message }}

{{ primaryMessage }}

{{ secondaryMessage }}

Copy after login

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 {} }
Copy after login

success, progress, failure, endedThese 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

javascriptcode.

// 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() } }
Copy after login

Here, we introduce the knowledge point of

rxjs,RxJSis a reactive programming library usingObservables, 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

debounceanti-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...

call

Because this one For global services, we call this component in

app.component.html:

// app.component.html  
Copy after login

For the convenience of demonstration, we add it in

user-list.component.htmlButton to facilitate triggering the demonstration:

// user-list.component.html 
Copy after login

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) }
Copy after login
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.

For more programming-related knowledge, please visit:

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!

Related labels:
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!