在catchError中使用路由器进行重定向是一种通用的解决方法。在处理错误时,可以使用Router.navigate / Router.navigateByUrl重定向到特定页面或组件。
import { Router } from '@angular/router'; import { ... catchError } from 'rxjs/operators';
@Injectable() export class MyService { constructor(private router: Router) {}
handleError(error: Error) { this.router.navigate(['/error']); return throwError(error); }
fetchData() { return this.http.get('/api/data').pipe( catchError((error) => this.handleError(error)) ); } }
Toastr是一种常见的JavaScript框架,用于在UI中显示通知。可以在Angular中使用Toastr来显示错误消息。
import { ToastrService } from 'ngx-toastr'; import { ... catchError } from 'rxjs/operators';
@Injectable() export class MyService { constructor(private toastr: ToastrService) {}
handleError(error: Error) { this.toastr.error('An error occurred'); return throwError(error); }
fetchData() { return this.http.get('/api/data').pipe( catchError((error) => this.handleError(error)) ); } }