要捕获Angular中的404 API消息,您可以使用HttpInterceptor来拦截Http请求并处理错误。
首先,创建一个名为HttpErrorInterceptor
的新的HttpInterceptor类:
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
intercept(request: HttpRequest, next: HttpHandler): Observable> {
return next.handle(request).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 404) {
// 处理404错误的逻辑
console.log("API not found");
}
return throwError(error);
})
);
}
}
然后,在您的AppModule
中将HttpErrorInterceptor
添加到提供者列表中:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { HttpErrorInterceptor } from './http-error.interceptor';
@NgModule({
declarations: [
// ...
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: HttpErrorInterceptor,
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule { }
现在,每当发生404错误时,HttpErrorInterceptor
中的逻辑将被执行,并且您可以根据需要进行处理。在示例中,我们只是在控制台上打印了一条消息。
请确保正确导入和配置HttpClientModule
和其他相关模块。