要捕获错误并使用拦截器模拟错误响应,您可以按照以下步骤操作:
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
intercept(request: HttpRequest, next: HttpHandler): Observable> {
return next.handle(request).pipe(
catchError((error: HttpErrorResponse) => {
console.log('ErrorInterceptor: ', error); // 打印错误信息
return throwError(error); // 将错误抛出
})
);
}
}
providers
数组中:import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { ErrorInterceptor } from './error.interceptor';
@NgModule({
imports: [
HttpClientModule
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: ErrorInterceptor,
multi: true
}
]
})
export class AppModule { }
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class DataService {
constructor(private http: HttpClient) { }
getData() {
return this.http.get('https://api.example.com/data').subscribe(
(response) => {
console.log('Response: ', response);
},
(error) => {
console.log('Error: ', error);
}
);
}
}
get()
方法更改URL为一个不存在的URL,例如:getData() {
return this.http.get('https://api.example.com/nonexistent').subscribe(
(response) => {
console.log('Response: ', response);
},
(error) => {
console.log('Error: ', error);
}
);
}
这样,当发生错误时,拦截器将捕获错误并将其抛出,您可以在服务中订阅错误并处理它。