溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Angular怎么自定義notification

發(fā)布時(shí)間:2022-12-02 09:36:29 來(lái)源:億速云 閱讀:105 作者:iii 欄目:web開發(fā)

今天小編給大家分享一下Angular怎么自定義notification的相關(guān)知識(shí)點(diǎn),內(nèi)容詳細(xì),邏輯清晰,相信大部分人都還太了解這方面的知識(shí),所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來(lái)了解一下吧。

效果圖如下:

Angular怎么自定義notification

添加服務(wù)

我們?cè)?app/services 中添加 notification.service.ts 服務(wù)文件(請(qǐng)使用命令行生成),添加相關(guān)的內(nèi)容:

// notification.service.ts

import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';

// 通知狀態(tài)的枚舉
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: ''
  }

  // 轉(zhuǎn)換成可觀察體
  public getNotification(): Observable<NotificationStatus> {
    return this.notify.asObservable();
  }

  // 進(jìn)行中通知
  public showProcessNotification() {
    this.notify.next(NotificationStatus.Process)
  }

  // 成功通知
  public showSuccessNotification() {
    this.notify.next(NotificationStatus.Success)
  }

  // 結(jié)束通知
  public showEndedNotification() {
    this.notify.next(NotificationStatus.Ended)
  }

  // 更改信息
  public changePrimarySecondary(primary?: string, secondary?: string) {
    this.messageObj.primary = primary;
    this.messageObj.secondary = secondary
  }

  constructor() { }
}

是不是很容易理解...

我們將 notify 變成可觀察物體,之后發(fā)布各種狀態(tài)的信息。

創(chuàng)建組件

我們?cè)?app/components 這個(gè)存放公共組件的地方新建 notification 組件。所以你會(huì)得到下面的結(jié)構(gòu):

notification                                          
├── notification.component.html                     // 頁(yè)面骨架
├── notification.component.scss                     // 頁(yè)面獨(dú)有樣式
├── notification.component.spec.ts                  // 測(cè)試文件
└── notification.component.ts                       // javascript 文件

我們定義 notification 的骨架:

<!-- notification.component.html -->

<!-- 支持手動(dòng)關(guān)閉通知 -->
<button (click)="closeNotification()">關(guān)閉</button>
<h2>提醒的內(nèi)容: {{ message }}</h2>
<!-- 自定義重點(diǎn)通知信息 -->
<p>{{ primaryMessage }}</p>
<!-- 自定義次要通知信息 -->
<p>{{ secondaryMessage }}</p>

接著,我們簡(jiǎn)單修飾下骨架,添加下面的樣式:

// 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 的內(nèi)容,在出現(xiàn)通知的時(shí)候才有
  &.active {
    top: 10px;
  }
  &.success {}
  &.progress {}
  &.failure {}
  &.ended {}
}

success, progress, failure, ended 這四個(gè)類名對(duì)應(yīng) notification service 定義的枚舉,可以按照自己的喜好添加相關(guān)的樣式。

最后,我們添加行為 javascript 代碼。

// notification.component.ts

import { Component, OnInit, HostBinding, OnDestroy } from '@angular/core';
// 新的知識(shí)點(diǎn) rxjs
import { Subscription } from 'rxjs';
import {debounceTime} from 'rxjs/operators';
// 引入相關(guān)的服務(wù)
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 {
  
  // 防抖時(shí)間,只讀
  private readonly NOTIFICATION_DEBOUNCE_TIME_MS = 200;
  
  protected notificationSubscription!: Subscription;
  private timer: any = null;
  public message: string = ''
  
  // notification service 枚舉信息的映射
  private reflectObj: any = {
    progress: "進(jìn)行中",
    success: "成功",
    failure: "失敗",
    ended: "結(jié)束"
  }

  @HostBinding('class') notificationCssClass = '';

  public primaryMessage!: string;
  public secondaryMessage!: string;

  constructor(
    private notificationService: NotificationService
  ) { }

  ngOnInit(): void {
    this.init()
  }

  public init() {
    // 添加相關(guān)的訂閱信息
    this.notificationSubscription = this.notificationService.getNotification()
      .pipe(
        debounceTime(this.NOTIFICATION_DEBOUNCE_TIME_MS)
      )
      .subscribe((notificationStatus: NotificationStatus) => {
        if(notificationStatus) {
          this.resetTimeout();
          // 添加相關(guān)的樣式
          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 = ''
  }
  
  // 關(guān)閉定時(shí)器
  private resetTimeout(): void {
    if(this.timer) {
      clearTimeout(this.timer)
    }
  }

  // 關(guān)閉通知
  public closeNotification() {
    this.notificationCssClass = ''
    this.resetTimeout()
  }
  
  // 組件銷毀
  ngOnDestroy(): void {
    this.resetTimeout();
    // 取消所有的訂閱消息
    this.notificationSubscription.unsubscribe()
  }

}

在這里,我們引入了 rxjs 這個(gè)知識(shí)點(diǎn),RxJS 是使用 Observables 的響應(yīng)式編程的庫(kù),它使編寫異步或基于回調(diào)的代碼更容易。這是一個(gè)很棒的庫(kù),接下來(lái)的很多文章你會(huì)接觸到它更多的內(nèi)容。

這里我們使用了 debounce 防抖函數(shù),函數(shù)防抖,就是指觸發(fā)事件后,在 n 秒后只能執(zhí)行一次,如果在 n 秒內(nèi)又觸發(fā)了事件,則會(huì)重新計(jì)算函數(shù)的執(zhí)行時(shí)間。簡(jiǎn)單來(lái)說(shuō):當(dāng)一個(gè)動(dòng)作連續(xù)觸發(fā),只執(zhí)行最后一次。

ps: throttle 節(jié)流函數(shù):限制一個(gè)函數(shù)在一定時(shí)間內(nèi)只能執(zhí)行一次。

調(diào)用

因?yàn)檫@個(gè)一個(gè)全局的服務(wù),我們?cè)?app.component.html 中調(diào)用此組件:

// app.component.html

<router-outlet></router-outlet>
<app-notification></app-notification>

為了方便演示,我們?cè)?user-list.component.html 中添加按鈕,方便觸發(fā)演示:

// user-list.component.html

<button (click)="showNotification()">click show notification</button>

觸發(fā)相關(guān)的代碼:

// 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)
}

以上就是“Angular怎么自定義notification”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會(huì)為大家更新不同的知識(shí),如果還想學(xué)習(xí)更多的知識(shí),請(qǐng)關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI