이 글은 여러분이 angular를 계속 학습하고 Angle의 맞춤 서비스 알림을 간략하게 이해하는 데 도움이 될 것입니다. 모두에게 도움이 되기를 바랍니다!
이전 기사에서 다음을 언급했습니다.
서비스는 API 요청을 처리하는 데 사용될 수 있을 뿐만 아니라 다른 용도로도 사용할 수 있습니다.
예를 들어, 이 기사에서 설명할 알림
구현. [관련 튜토리얼 권장 사항: "notification
的实现。【相关教程推荐:《angular教程》】
效果图如下:
UI 这个可以后期调整
So,我们一步步来分解。
添加服务
我们在 app/services
中添加 notification.service.ts
服务文件(请使用命令行生成),添加相关的内容:
// 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
的骨架:
<!-- notification.component.html --> <!-- 支持手动关闭通知 --> <button (click)="closeNotification()">关闭</button> <h1 id="提醒的内容-nbsp-nbsp-message-nbsp">提醒的内容: {{ message }}</h1> <!-- 自定义重点通知信息 --> <p>{{ primaryMessage }}</p> <!-- 自定义次要通知信息 --> <p>{{ secondaryMessage }}</p>
接着,我们简单修饰下骨架,添加下面的样式:
// 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
这四个类名对应 notification service 定义的枚举,可以按照自己的喜好添加相关的样式。
最后,我们添加行为 javascript
代码。
// 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() } }
在这里,我们引入了 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>
触发相关的代码:
// 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) }
至此,大功告成,我们成功模拟了 notification
angular tutorial
서비스 추가
🎜app/services
에 notification.service.ts 서비스 파일(생성하려면 명령줄을 사용하세요), 관련 콘텐츠 추가: 🎜rrreee🎜이해하기 쉬운가요...🎜🎜<code>notify
를 관찰 가능한 객체로 변환한 다음 게시하겠습니다. 각 상태 정보. 🎜구성요소 생성
🎜공개 구성요소가 있는app/comComponents
에 새로운 알림을 생성합니다. 저장된
구성 요소. 따라서 다음과 같은 구조를 얻게 됩니다: 🎜rrreee🎜 알림
의 뼈대를 정의합니다: 🎜rrreee🎜그런 다음 간단히 뼈대를 수정하고 다음 스타일을 추가합니다: 🎜rrreee🎜success, Progress , failure,ended
이 네 가지 클래스 이름은 알림 서비스에서 정의한 열거형에 해당합니다. 자신의 기본 설정에 따라 관련 스타일을 추가할 수 있습니다. 🎜🎜마지막으로 동작 javascript
코드를 추가합니다. 🎜rrreee🎜여기서 rxjs의 지식 포인트를 소개합니다. RxJS는 Observables
를 사용하여 비동기 또는 콜백을 작성하는 반응형 프로그래밍 라이브러리입니다. 기반 코드가 더 쉽습니다. 이것은 훌륭한 라이브러리이며 다음 기사에서 이에 대해 자세히 알아볼 것입니다. 🎜🎜여기서는 debounce
흔들림 방지 기능을 사용합니다. 흔들림 방지 기능은 이벤트가 트리거된 후 이벤트가 다시 트리거되면 한 번만 실행할 수 있음을 의미합니다. n초 이내에 함수의 실행 시간이 다시 계산됩니다. 간단히 말하면, 작업이 연속적으로 트리거되면 마지막 시간만 실행됩니다. 🎜🎜🎜ps: throttle
Throttle 기능: 특정 기간 내에 한 번만 실행되도록 기능을 제한합니다. 🎜🎜🎜면접 때 면접관이 자주 하는 질문은...🎜전화
🎜글로벌 서비스이기 때문에 우리는 전화를 겁니다.app.comComponent.html
의 이 구성 요소: 🎜rrreee🎜 데모를 용이하게 하기 위해 user-list.comComponent.html
에 버튼을 추가하여 데모를 쉽게 실행할 수 있습니다. 🎜 rrreee 🎜트리거 관련 코드:🎜rrreee🎜이제 우리는 알림
기능을 성공적으로 시뮬레이션했습니다. 실제 요구 사항에 따라 관련 서비스 구성 요소를 수정하고 비즈니스 요구 사항에 맞게 사용자 정의할 수 있습니다. 내부용 시스템을 개발하는 경우 성숙한 UI 라이브러리를 사용하는 것이 좋습니다. 이를 통해 다양한 구성 요소와 서비스를 캡슐화하여 개발 시간을 많이 절약할 수 있습니다. 🎜🎜【끝】✅🎜🎜프로그래밍 관련 지식을 더 보려면 🎜프로그래밍 교육🎜을 방문하세요! ! 🎜위 내용은 각도 학습 채팅 알림(맞춤 서비스)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

JavaScript 不提供任何内存管理操作。相反,内存由 JavaScript VM 通过内存回收过程管理,该过程称为垃圾收集。

Node 19已正式发布,下面本篇文章就来带大家详解了解一下Node.js 19的 6 大特性,希望对大家有所帮助!

vscode自身是支持vue文件组件跳转到定义的,但是支持的力度是非常弱的。我们在vue-cli的配置的下,可以写很多灵活的用法,这样可以提升我们的生产效率。但是正是这些灵活的写法,导致了vscode自身提供的功能无法支持跳转到文件定义。为了兼容这些灵活的写法,提高工作效率,所以写了一个vscode支持vue文件跳转到定义的插件。

选择一个Node的Docker镜像看起来像是一件小事,但是镜像的大小和潜在漏洞可能会对你的CI/CD流程和安全造成重大的影响。那我们如何选择一个最好Node.js Docker镜像呢?

本篇文章给大家整理和分享几个前端文件处理相关的实用工具库,共分成6大类一一介绍给大家,希望对大家有所帮助。


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

드림위버 CS6
시각적 웹 개발 도구

SecList
SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

mPDF
mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.
