面试题答案
一键面试整体设计方案
- 错误信息记录:利用Angular的HTTP拦截器,在请求发生错误时捕获错误信息,并将其记录到日志中。
- 自动重试机制:使用RxJS操作符来实现自动重试逻辑,在特定次数内尝试重新发起请求。
涉及的RxJS操作符
- catchError:用于捕获HTTP请求中的错误,以便进行错误处理和日志记录。
- retryWhen:实现自动重试机制,根据设定的重试次数和重试条件重新发起请求。
结合拦截器实现功能
- 创建HTTP拦截器:
import { Injectable } from '@angular/core';
import {
HttpEvent,
HttpHandler,
HttpInterceptor,
HttpRequest,
} from '@angular/common/http';
import { Observable, catchError, retryWhen } from 'rxjs';
@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
catchError((error) => {
// 记录详细错误信息到日志
console.error('HTTP Request Error:', error);
throw error;
}),
retryWhen((errors) =>
errors.pipe(
// 设定重试次数,例如3次
retry(3),
// 可以在此添加重试条件逻辑
// 比如根据特定的HTTP状态码重试
// filter((error) => error.status === 500)
)
)
);
}
}
- 注册拦截器:在
app.module.ts
中注册拦截器:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform - browser';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppComponent } from './app.component';
import { HttpErrorInterceptor } from './http - error.interceptor';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, HttpClientModule],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: HttpErrorInterceptor,
multi: true,
},
],
bootstrap: [AppComponent],
})
export class AppModule {}
通过上述步骤,当Angular的HTTP请求发生错误时,错误信息会被记录到日志中,并且会根据设定的重试次数尝试重新发起请求。