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

Angular 8中如何用SnackBar实现非集中式重复条目错误处理

Handling Duplicate Client Errors with Angular 8 SnackBar (Non-Centralized Approach)

Got it, let's fix that duplicate client error handling for your client.add.component.ts code. Since you want a non-centralized solution (meaning we handle errors directly in this component's subscription), here's exactly how to integrate the MatSnackBar into your existing logic:

First, double-check you've got MatSnackBar imported and injected into your component (I assume you already have this set up, but just to be thorough):

import { MatSnackBar } from '@angular/material/snack-bar';

// In your component's constructor
constructor(
  private clientsSvc: ClientsService,
  private router: Router,
  private route: ActivatedRoute,
  private snackBar: MatSnackBar // Make sure this is injected
) {}

Now modify your subscription to include an error callback. This is where we'll check for duplicate entries (based on the 503 error you mentioned, or adjust the condition if your backend returns a different status/code for duplicates) and trigger the SnackBar:

this.clientsSvc.createClient(client).subscribe(
  // Success callback: navigate as before
  (x) => {
    this.router.navigate(['../'], { relativeTo: this.route });
  },
  // Error callback: handle duplicate and other errors
  (error) => {
    // Adjust this condition to match how your backend signals duplicate entries
    // For example, if the error response has a message containing "Duplicate", or uses a 409 status code
    if (error.status === 503 || (error.error?.message && error.error.message.includes('Duplicate'))) {
      this.snackBar.open(`Duplicate Client Name`, null, { duration: 3000 });
    } else {
      // Fallback for other unexpected errors
      this.snackBar.open(`Failed to create client. Please try again later.`, null, { duration: 3000 });
    }
  }
);

Key Notes:

  • Non-centralized handling: This keeps the error logic tied directly to this specific API call, which is what you asked for instead of a global error handler like an HTTP interceptor.
  • Error condition adjustment: 503 typically means "Service Unavailable"—if your backend actually uses a different status code for duplicates (like 409 Conflict), swap that in for error.status === 409 instead. You can also check the error response body's message if the backend sends a descriptive error.
  • SnackBar configuration: The null parameter skips adding an action button, and duration: 3000 makes the message auto-close after 3 seconds.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 21:02:54