Angular 8中如何用SnackBar实现非集中式重复条目错误处理
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 === 409instead. You can also check the error response body's message if the backend sends a descriptive error. - SnackBar configuration: The
nullparameter skips adding an action button, andduration: 3000makes the message auto-close after 3 seconds.
内容的提问来源于stack exchange,提问作者smiti

