You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中如何基于动态告警数组管理唯一通知的增删?

Angular 告警通知服务实现方案

1. 扩展告警数据结构

基于你现有的IAlert接口,直接用name作为唯一标识即可,无需额外添加ID:

export interface IAlert {
  name: string;
  isActive: boolean;
}

2. 实现告警通知服务

用BehaviorSubject维护活跃告警列表,确保组件订阅时能获取当前已有数据,核心逻辑处理告警的新增、更新和移除:

import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { IAlert } from './alert.interface';

@Injectable({ providedIn: 'root' })
export class AlertNotificationService {
  // BehaviorSubject存储当前活跃告警,初始为空数组
  private activeAlerts$ = new BehaviorSubject<IAlert[]>([]);
  // 对外暴露只读Observable,避免外部直接修改数据
  public alerts$: Observable<IAlert[]> = this.activeAlerts$.asObservable();

  constructor() {}

  // 处理SignalR推送的告警数据
  handleAlert(alert: IAlert): void {
    const currentAlerts = this.activeAlerts$.value;
    const existingAlertIndex = currentAlerts.findIndex(a => a.name === alert.name);

    if (alert.isActive) {
      // 告警激活:不存在则添加,存在则更新状态
      if (existingAlertIndex === -1) {
        this.activeAlerts$.next([...currentAlerts, alert]);
      } else {
        const updatedAlerts = [...currentAlerts];
        updatedAlerts[existingAlertIndex] = alert;
        this.activeAlerts$.next(updatedAlerts);
      }
    } else {
      // 告警清除:移除对应项
      if (existingAlertIndex !== -1) {
        const updatedAlerts = currentAlerts.filter(a => a.name !== alert.name);
        this.activeAlerts$.next(updatedAlerts);
      }
    }
  }

  // 用户确认告警,移除通知
  confirmAlert(alertName: string): void {
    const currentAlerts = this.activeAlerts$.value;
    const updatedAlerts = currentAlerts.filter(a => a.name !== alertName);
    this.activeAlerts$.next(updatedAlerts);
    // 可选:此处调用后端API,标记告警已确认
  }
}

3. SignalR服务集成告警处理

在你的SignalR服务中,监听后端推送的告警事件并调用通知服务:

import { Injectable } from '@angular/core';
import { HubConnection, HubConnectionBuilder } from '@microsoft/signalr';
import { AlertNotificationService } from './alert-notification.service';
import { IAlert } from './alert.interface';

@Injectable({ providedIn: 'root' })
export class SignalRAlertService {
  private hubConnection: HubConnection;

  constructor(private alertNotificationService: AlertNotificationService) {
    this.initConnection();
  }

  private initConnection(): void {
    this.hubConnection = new HubConnectionBuilder()
      .withUrl('/alertHub') // 替换为你的SignalR Hub地址
      .build();

    this.hubConnection.start().catch(err => console.error('SignalR连接失败:', err));

    // 监听后端推送的告警
    this.hubConnection.on('ReceiveAlert', (alert: IAlert) => {
      this.alertNotificationService.handleAlert(alert);
    });
  }
}

4. 告警通知组件实现

订阅告警数据并渲染列表,提供确认按钮:

import { Component, OnInit } from '@angular/core';
import { AlertNotificationService } from '../alert-notification.service';
import { IAlert } from '../alert.interface';

@Component({
  selector: 'app-alert-notification',
  template: `
    <div class="alert-panel">
      <div *ngFor="let alert of activeAlerts" class="alert-card">
        <span>{{ alert.name }}</span>
        <button class="confirm-btn" (click)="confirmAlert(alert.name)">确认</button>
      </div>
    </div>
  `,
  styles: [`
    .alert-panel { position: fixed; top: 20px; right: 20px; z-index: 9999; }
    .alert-card { padding: 12px 16px; margin: 8px 0; background: #ffebee; border-radius: 4px; display: flex; justify-content: space-between; align-items: center; }
    .confirm-btn { padding: 4px 8px; background: #ef5350; color: white; border: none; border-radius: 2px; cursor: pointer; }
  `]
})
export class AlertNotificationComponent implements OnInit {
  activeAlerts: IAlert[] = [];

  constructor(private alertNotificationService: AlertNotificationService) {}

  ngOnInit(): void {
    this.alertNotificationService.alerts$.subscribe(alerts => {
      this.activeAlerts = alerts;
    });
  }

  confirmAlert(alertName: string): void {
    this.alertNotificationService.confirmAlert(alertName);
  }
}

5. 全局引入通知组件

在根组件模板中添加通知组件,确保应用启动后即可接收并展示告警:

<app-alert-notification></app-alert-notification>
<!-- 其他应用内容 -->

内容的提问来源于stack exchange,提问作者nbren007

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 06:50:16