
이전 기사에서 우리는
서비스가 API 요청을 처리하는 데 사용될 수 있을 뿐만 아니라
이 기사에서 설명할 notification 구현과 같은 다른 용도도 있다고 언급했습니다. [추천 관련 튜토리얼: "Angular Tutorial"]
렌더링은 다음과 같습니다.

UI는 나중에 조정될 수
있으므로 단계별로 살펴보겠습니다.
서비스를 추가하려면
app/services 에 notification.service.ts 서비스 파일을 추가하고(생성하려면 명령줄을 사용하십시오) 관련 콘텐츠를 추가합니다:
//notification.service.ts
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
// 알림 상태 열거export enum NotificationStatus {
프로세스 = "진행",
성공 = "성공",
실패 = "실패",
종료됨 = "끝났어요"
}
@주입 가능({
제공됨: '루트'
})
내보내기 클래스 알림 서비스 {
개인 알림: 제목<NotificationStatus> = 새 제목();
공개 messageObj: 모두 = {
주요한: '',
보조: ''
}
// 관찰 가능한 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)
}
// 정보 변경 publicchangePrimarySecondary(primary?: string, second?: string) {
this.messageObj.primary = 기본;
this.messageObj.secondary = 보조
}
생성자() { }
} 이해하기 쉽나요...
notify 관찰 가능한 객체로 변환한 다음 다양한 상태 정보를 게시합니다.
구성 요소를 생성하려면
공용 구성 요소가 저장되어 있는 app/components 에 새 notification 구성 요소를 만듭니다. 따라서 다음과 같은 구조를 얻게 됩니다:
알림 >
notification 의 뼈대를 정의하는
자바스크립트 파일:
<!--notification.comComponent.html -->
<!--알림 수동 닫기 지원-->
<button (click)="closeNotification()">닫기</button>
<h1>알림 내용: {{ 메시지 }}</h1>
<!-- 주요 알림 정보 사용자 정의-->
<p>{{ 기본 메시지 }}</p>
<!-- 보조 알림 정보 사용자 정의-->
<p>{{ secondMessage }}</p> 다음으로 간단히 골격을 수정하고 다음 스타일을 추가합니다.
//notification.comComponent.scss
:주인 {
위치: 고정;
상단: -100%;
오른쪽: 20px;
배경색: #999;
테두리: 1px 실선 #333;
테두리 반경: 10px;
너비: 400px;
높이: 180px;
패딩: 10px;
// 여기서는 active 내용에 주의하세요. &.active {
상단: 10px;
}
&.성공{}
&.진전 {}
&.실패 {}
&.종료됨 {}
} success, progress, failure, ended 의 네 가지 클래스 이름은 알림 서비스에서 정의한 열거형에 해당하며 사용자의 취향에 따라 관련 스타일을 추가할 수 있습니다.
마지막으로 행동 javascript 코드를 추가합니다.
// 알림.구성요소.ts
import { Component, OnInit, HostBinding, OnDestroy } from '@angular/core';
//새로운 지식 포인트 rxjs
'rxjs'에서 { 구독 }을 가져옵니다.
'rxjs/operators'에서 {debounceTime}을 가져옵니다.
//관련 서비스 소개 import {NotificationStatus,NotificationService } from 'src/app/services/notification.service';
@요소({
선택기: '앱 알림',
templateUrl: './notification.comComponent.html',
styleUrls: ['./notification.comComponent.scss']
})
내보내기 클래스 알림 구성요소는 OnInit, OnDestroy를 구현합니다.
// 흔들림 방지 시간, 읽기 전용 전용 읽기 전용 NOTIFICATION_DEBOUNCE_TIME_MS = 200;
보호된 알림Subscription!: 구독;
개인 타이머: 모두 = null;
공개 메시지: 문자열 = ''
// 열거 정보의 알림 서비스 매핑 private ReflectObj: any = {
진행: "진행 중",
성공: "성공",
실패: "실패",
종료됨: "끝"
}
@HostBinding('class')notificationCssClass = '';
공개 기본 메시지!: 문자열;
공개 보조 메시지!: 문자열;
건설자(
비공개 알림 서비스: 알림 서비스
) { }
ngOnInit(): 무효 {
this.init()
}
공개 초기화() {
//관련 구독 정보 추가 this.notificationSubscription = this.notificationService.getNotification()
.파이프(
디바운스타임(this.NOTIFICATION_DEBOUNCE_TIME_MS)
)
.subscribe((notificationStatus: 알림상태) => {
if(알림상태) {
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 === 알림상태.프로세스) {
this.resetTimeout()
this.timer = setTimeout(() => {
this.resetView()
}, 1000)
} 또 다른 {
this.resetTimeout();
this.timer = setTimeout(() => {
this.notificationCssClass = ''
this.resetView()
}, 2000)
}
}
})
}
개인 ResetView(): 무효 {
this.message = ''
}
// 타이머를 닫습니다. private ResetTimeout(): void {
if(this.timer) {
클리어타임아웃(this.timer)
}
}
// 알림 닫기 public closeNotification() {
this.notificationCssClass = ''
this.resetTimeout()
}
// 컴포넌트가 파괴됨 ngOnDestroy(): void {
this.resetTimeout();
//모든 구독 메시지 취소 this.notificationSubscription.unsubscribe()
}
} 여기에서는 rxjs 의 지식 포인트를 소개합니다. RxJS 는 Observables 사용하는 반응형 프로그래밍 라이브러리로, 비동기 또는 콜백 기반 코드를 더 쉽게 작성할 수 있습니다. 이것은 훌륭한 라이브러리이며 다음 몇 가지 기사에서 이에 대해 자세히 알아볼 것입니다.
여기서는 debounce 방지 기능을 사용합니다. 흔들림 방지 기능은 이벤트가 발생한 후 n초 후에 한 번만 실행될 수 있음을 의미합니다. 다시 계산되었습니다. 간단히 말하면, 작업이 연속적으로 트리거되면 마지막 시간만 실행됩니다.
ps:
throttle스로틀링 기능: 일정 시간 내에 한 번만 실행되도록 기능을 제한합니다 .
인터뷰 중에 면접관은 다음과 같은 질문을 좋아합니다...
Calling
글로벌 서비스이기 때문에 app.component.html 에서 이 컴포넌트를 호출합니다.
// app.comComponent.html <라우터 아웃렛></라우터 아웃렛> <app-notification></app-notification>
데모를 용이하게 하기 위해 user-list.component.html 에 데모를 쉽게 트리거할 수 있는 버튼을 추가합니다.
// user-list.comComponent.html <button (click)="showNotification()">알림 표시 클릭</button>
은 관련 코드를 트리거합니다:
// user-list.comComponent.ts
'src/app/services/notification.service'에서 {NotificationService }를 가져옵니다.
// ...
건설자(
비공개 알림 서비스: 알림 서비스
) { }
//알림 표시 showNotification(): void {
this.notificationService.changePrimarySecondary('기본 정보 1');
this.notificationService.showProcessNotification();
setTimeout(() => {
this.notificationService.changePrimarySecondary('1차 정보 2', '2차 정보 2');
this.notificationService.showSuccessNotification();
}, 1000)
} 이제 완료되었습니다. notification 기능을 성공적으로 시뮬레이션했습니다. 실제 요구 사항에 따라 관련 서비스 구성 요소를 수정하고 비즈니스 요구 사항에 맞게 사용자 정의할 수 있습니다. 내부용 시스템을 개발하는 경우 성숙한 UI 라이브러리를 사용하는 것이 좋습니다. 이를 통해 다양한 구성 요소와 서비스를 캡슐화하여 개발 시간을 많이 절약할 수 있습니다.