Maison > interface Web > js tutoriel > le corps du texte

Angular utilise le service pour implémenter des services personnalisés (notification)

青灯夜游
Libérer: 2022-04-29 21:12:04
avant
2535 Les gens l'ont consulté

Cet article vous aidera à continuer à apprendre angular et à découvrir comment Angular utilise le service pour mettre en œuvre des services personnalisés (notification). J'espère qu'il sera utile à tout le monde !

Angular utilise le service pour implémenter des services personnalisés (notification)

Dans l'article précédent, nous avons mentionné :

le service peut non seulement être utilisé pour traiter les requêtes API, mais a également d'autres utilisations

Par exemple, la notification dont nous parlerons dans cet article implémentation. [Recommandations du tutoriel associé : "notification 的实现。【相关教程推荐:《angular教程》】

效果图如下:

Angular utilise le service pour implémenter des services personnalisés (notification)

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: &#39;&#39;,
    secondary: &#39;&#39;
  }

  // 转换成可观察体
  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() { }
}
Copier après la connexion

是不是很容易理解...

我们将 notify 变成可观察物体,之后发布各种状态的信息。

创建组件

我们在 app/components 这个存放公共组件的地方新建 notification 组件。所以你会得到下面的结构:

notification                                          
├── notification.component.html                     // 页面骨架
├── notification.component.scss                     // 页面独有样式
├── notification.component.spec.ts                  // 测试文件
└── notification.component.ts                       // javascript 文件
Copier après la connexion

我们定义 notification 的骨架:

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

<!-- 支持手动关闭通知 -->
<button (click)="closeNotification()">关闭</button>
<h1>提醒的内容: {{ message }}</h1>
<!-- 自定义重点通知信息 -->
<p>{{ primaryMessage }}</p>
<!-- 自定义次要通知信息 -->
<p>{{ secondaryMessage }}</p>
Copier après la connexion

接着,我们简单修饰下骨架,添加下面的样式:

// 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 {}
}
Copier après la connexion

success, progress, failure, ended 这四个类名对应 notification service 定义的枚举,可以按照自己的喜好添加相关的样式。

最后,我们添加行为 javascript 代码。

// notification.component.ts

import { Component, OnInit, HostBinding, OnDestroy } from &#39;@angular/core&#39;;
// 新的知识点 rxjs
import { Subscription } from &#39;rxjs&#39;;
import {debounceTime} from &#39;rxjs/operators&#39;;
// 引入相关的服务
import { NotificationStatus, NotificationService } from &#39;src/app/services/notification.service&#39;;

@Component({
  selector: &#39;app-notification&#39;,
  templateUrl: &#39;./notification.component.html&#39;,
  styleUrls: [&#39;./notification.component.scss&#39;]
})
export class NotificationComponent implements OnInit, OnDestroy {
  
  // 防抖时间,只读
  private readonly NOTIFICATION_DEBOUNCE_TIME_MS = 200;
  
  protected notificationSubscription!: Subscription;
  private timer: any = null;
  public message: string = &#39;&#39;
  
  // notification service 枚举信息的映射
  private reflectObj: any = {
    progress: "进行中",
    success: "成功",
    failure: "失败",
    ended: "结束"
  }

  @HostBinding(&#39;class&#39;) notificationCssClass = &#39;&#39;;

  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 = &#39;&#39;
              this.resetView()
            }, 2000)
          }
        }
      })
  }

  private resetView(): void {
    this.message = &#39;&#39;
  }
  
  // 关闭定时器
  private resetTimeout(): void {
    if(this.timer) {
      clearTimeout(this.timer)
    }
  }

  // 关闭通知
  public closeNotification() {
    this.notificationCssClass = &#39;&#39;
    this.resetTimeout()
  }
  
  // 组件销毁
  ngOnDestroy(): void {
    this.resetTimeout();
    // 取消所有的订阅消息
    this.notificationSubscription.unsubscribe()
  }

}
Copier après la connexion

在这里,我们引入了 rxjs 这个知识点,RxJS 是使用 Observables 的响应式编程的库,它使编写异步或基于回调的代码更容易。这是一个很棒的库,接下来的很多文章你会接触到它更多的内容。

这里我们使用了 debounce 防抖函数,函数防抖,就是指触发事件后,在 n 秒后只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数的执行时间。简单来说:当一个动作连续触发,只执行最后一次。

ps: throttle 节流函数:限制一个函数在一定时间内只能执行一次

在面试的时候,面试官很喜欢问...

调用

因为这个一个全局的服务,我们在 app.component.html 中调用此组件:

// app.component.html

<router-outlet></router-outlet>
<app-notification></app-notification>
Copier après la connexion

为了方便演示,我们在 user-list.component.html 中添加按钮,方便触发演示:

// user-list.component.html

<button (click)="showNotification()">click show notification</button>
Copier après la connexion

触发相关的代码:

// user-list.component.ts

import { NotificationService } from &#39;src/app/services/notification.service&#39;;

// ...
constructor(
  private notificationService: NotificationService
) { }

// 展示通知
showNotification(): void {
  this.notificationService.changePrimarySecondary(&#39;主要信息 1&#39;);
  this.notificationService.showProcessNotification();
  setTimeout(() => {
    this.notificationService.changePrimarySecondary(&#39;主要信息 2&#39;, &#39;次要信息 2&#39;);
    this.notificationService.showSuccessNotification();
  }, 1000)
}
Copier après la connexion

至此,大功告成,我们成功模拟了 notificationTutoriel angulaire

"]

Le rendu est le suivant :

Angular utilise le service pour implémenter des services personnalisés (notification)🎜🎜🎜UI Cela peut être ajusté plus tard🎜🎜🎜Alors, décomposons-le étape par étape. 🎜🎜Ajouter un service🎜🎜Nous ajoutons notification.service dans <code>app/services . ts (veuillez utiliser la ligne de commande pour générer), ajoutez du contenu pertinent : 🎜rrreee🎜N'est-ce pas facile à comprendre...🎜🎜Nous allons transformer notify en un observable Objet,Publiez ensuite diverses informations sur l'état. 🎜🎜Créer un composant🎜🎜Nous créons une nouvelle application/composants où les composants publics sont stockésnotification. Vous obtiendrez donc la structure suivante :🎜rrreee🎜On définit le squelette de notification :🎜rrreee🎜Ensuite, on modifie simplement le squelette et on ajoute le style suivant :🎜rrreee🎜succès, progrès , échec, terminé Ces quatre noms de classes correspondent à l'énumération définie par le service de notification. Vous pouvez ajouter des styles associés selon vos propres préférences. 🎜🎜Enfin, nous ajoutons le code comportemental javascript. 🎜rrreee🎜Ici, nous introduisons le point de connaissance de rxjs RxJS est une bibliothèque de programmation réactive qui utilise des Observables, ce qui rend l'écriture asynchrone ou un rappel. le code basé sur est plus facile. C'est une excellente bibliothèque, et vous en apprendrez plus à ce sujet dans les prochains articles. 🎜🎜Ici, nous utilisons la fonction anti-shake debounce. La fonction anti-shake signifie qu'après le déclenchement d'un événement, il ne peut être exécuté qu'une fois après n secondes si l'événement est à nouveau déclenché. dans les n secondes, le temps d'exécution de la fonction sera recalculé. Pour faire simple : lorsqu’une action est déclenchée en continu, seule la dernière fois est exécutée. 🎜🎜🎜ps : throttle Fonction d'accélérateur : Limiter une fonction à être exécutée une seule fois dans une certaine période de temps. 🎜🎜🎜Pendant l'entretien, l'intervieweur aime demander...🎜🎜Appeler🎜🎜Parce qu'il s'agit d'un service global , nous appelons ce composant dans app.component.html : 🎜rrreee🎜Pour faciliter la démonstration, nous ajoutons un bouton dans user-list.component.html pour un déclenchement facile Démo : 🎜rrreee🎜Code associé au déclencheur : 🎜rrreee🎜À ce stade, nous avons terminé, nous avons simulé avec succès la fonction de notification. Nous pouvons modifier les composants de service associés en fonction des besoins réels et les personnaliser pour répondre aux besoins de l'entreprise. Si nous développons un système à usage interne, il est recommandé d'utiliser des bibliothèques d'interface utilisateur matures. Elles nous ont aidé à encapsuler divers composants et services, nous faisant gagner beaucoup de temps de développement. 🎜🎜Pour plus de connaissances sur la programmation, veuillez visiter : 🎜Introduction à la programmation🎜 ! ! 🎜

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Étiquettes associées:
source:juejin.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!