In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces the relevant knowledge of "how Angular uses service to achieve custom services". The editor shows you the operation process through an actual case, and the operation method is simple, fast and practical. I hope that this article "how Angular uses service to achieve custom services" can help you solve the problem.
Add Servic
We add the notification.service.ts service file to app/services (please use command line generation) to add related content:
/ notification.service.tsimport {Injectable} from'@ angular/core';import {Observable, Subject} from 'rxjs';// Notification status enumeration 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:'} / / convert to observable body public getNotification (): Observable {return this.notify.asObservable () } / / Notification in progress public showProcessNotification () {this.notify.next (NotificationStatus.Process)} / / Notification public showSuccessNotification () {this.notify.next (NotificationStatus.Success)} / / end Notification public showEndedNotification () {this.notify.next (NotificationStatus.Ended)} / / change Information public changePrimarySecondary (primary?: string, secondary?: string) {this.messageObj.primary = primary This.messageObj.secondary = secondary} constructor () {}}
Is it easy to understand?
We turn the notify into an observable object, and then publish information about various states.
Create a component
We create a new notification component in app/components, where the common components are stored. So you get the following structure:
Notification ├── notification.component.html / / Page skeleton ├── notification.component.scss / / Page unique style ├── notification.component.spec.ts / / Test file └── notification.component.ts / / javascript file
We define the skeleton of notification:
Turn off the reminder: {{message}}
{{primaryMessage}}
{{secondaryMessage}}
Next, we simply retouch the skeleton and add the following styles:
/ / 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; / / Note the content of active here, which is available only at the time of notification & .active {top: 10px;} & .success {} & .progress} & .failure {} & .ended {}
The four class names success, progress, failure, and ended correspond to the enumerations defined by notification service, and you can add related styles as you like.
Finally, we add the behavior javascript code.
/ / notification.component.tsimport {Component, OnInit, HostBinding, OnDestroy} from'@ angular/core';// New knowledge point rxjsimport {Subscription} from 'rxjs';import {debounceTime} from' rxjs/operators';// introduces related services 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 {/ / anti-shake time, read-only private readonly NOTIFICATION_DEBOUNCE_TIME_MS = 200; protected notificationSubscripting: Subscription; private timer: any = null Public message: string =''/ / notification service enumeration information mapping private reflectObj: any = {progress: "in progress", success: "success", failure: "failure", ended: "end"} @ HostBinding ('class') notificationCssClass =''; public messages: string; public secondaryMessagemessages: string Constructor (private notificationService: NotificationService) {} ngOnInit (): void {this.init ()} public init () {/ / add relevant subscription information this.notificationSubscription = this.notificationService.getNotification () .pipe (debounceTime (this.NOTIFICATION_DEBOUNCE_TIME_MS)) .subscribe ((notificationStatus: NotificationStatus) = > {if (notificationStatus) {this.resetTimeout ()) / / add relevant styles this.notificationCssClass = `active ${notificationStatus} `this.message = this.reflectObj [notificationStatus] / / get custom primary information this.primaryMessage = this.notificationService.messageObj.primary; / / get custom secondary information 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 =''} / / turn off timer private resetTimeout (): void {if (this.timer) {clearTimeout (this.timer)}} / / close notification public closeNotification () {this.notificationCssClass =''this.resetTimeout ()} / / component pin Destroy ngOnDestroy (): void {this.resetTimeout () / / cancel all subscription messages this.notificationSubscription.unsubscribe ()}}
Here, we introduce the knowledge point of rxjs, a responsive programming library using Observables that makes it easier to write asynchronous or callback-based code. This is a great library, and you will learn more about it in many articles to follow.
Here, we use the debounce anti-shake function, which means that after triggering an event, it can only be executed once after n seconds. If the event is triggered within n seconds, the execution time of the function will be recalculated. To put it simply: when an action is triggered continuously, it is only executed for the last time.
Ps: throttle throttling function: restricts a function to be executed only once in a certain period of time.
During the interview, the interviewer likes to ask.
Call
Because of this global service, we call this component in app.component.html:
/ / app.component.html
To facilitate the demonstration, we add buttons in user-list.component.html to facilitate triggering the demonstration:
/ / user-list.component.htmlclick show notification
Trigger the related code:
/ / user-list.component.tsimport {NotificationService} from 'src/app/services/notification.service';//... constructor (private notificationService: NotificationService) {} / / display notification showNotification (): void {this.notificationService.changePrimarySecondary (' primary information 1'); this.notificationService.showProcessNotification (); setTimeout () = > {this.notificationService.changePrimarySecondary ('primary information 2', 'secondary information 2'); this.notificationService.showSuccessNotification () }, 1000)} this is the end of the introduction to "how Angular uses service to implement custom services". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.