Angular捕获HTTP异常:输入无效账号密码时如何显示错误信息?
Got it, let's fix this so you can show clear error messages when users enter invalid username/password combinations. Here's how to adjust your code step by step:
user.service Login Method Right now your login method only handles successful responses—we need to add logic to catch and process failed requests (like 401 Unauthorized, which is the standard status code for invalid credentials).
We'll use RxJS's catchError operator (make sure you're importing the right RxJS utilities for your Angular version):
// Import required RxJS operators first import { catchError, map } from 'rxjs/operators'; import { throwError } from 'rxjs'; login(accountCredentials: AccountCredentials): Observable<boolean> { return this.http.post(UrlHelper.routeTo("auth/login"), JSON.stringify(accountCredentials)) .pipe( map(n => { this.authService.setToken(n.json().token); this.globalEventsManager.login.emit(); return true; }), catchError(error => { // Handle specific error cases if (error.status === 401) { // Custom message for invalid credentials return throwError('Invalid username or password. Please try again.'); } // Catch-all for other errors return throwError('Something went wrong. Please check your connection and try again.'); }) ); }
Once the service is set up to emit errors, you need to listen for them in the component where you call the login method. Here's an example of how to display the error to the user:
// In your login component errorMessage: string = ''; onSubmitLogin() { this.errorMessage = ''; // Clear previous errors this.userService.login(this.accountCredentials) .subscribe({ next: (success) => { // Login success logic (e.g., redirect to dashboard) }, error: (errMsg) => { // Display the error message in your template this.errorMessage = errMsg; // Or use a UI library component (like toast/alert) // this.notificationService.showError(errMsg); } }); }
Then in your component's template, add something like this to show the error:
<div *ngIf="errorMessage" class="error-message"> {{ errorMessage }} </div>
http.service) If you want to handle 401 errors across your entire app (not just login), you can add global error interception in your http.service:
import { catchError } from 'rxjs/operators'; import { throwError } from 'rxjs'; request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> { return super.request(url, options).pipe( catchError(error => { if (error.status === 401) { // Emit a global event or throw a consistent error return throwError('Invalid credentials'); } // Handle other error types as needed return throwError(error.message || 'Server error occurred'); }) ); }
Important Note:
Make sure your backend returns a 401 Unauthorized status code when credentials are invalid—this is the standard way for APIs to signal authentication failures. If your backend returns a 200 status with an error message in the response body, you'll need to adjust the map operator to check for that instead of using catchError.
内容的提问来源于stack exchange,提问作者user2102355

