Angular HttpClient重复发起GET请求问题排查求助
Angular HttpClient GET请求:浏览器显示1次但Spring Boot Reactive后端收到2次
Angular的HttpClient发起GET请求时,浏览器开发者工具的网络面板仅显示1次请求,但Spring Boot Reactive后端的请求日志显示该GET请求被触发了2次。
已尝试的操作
- 检查浏览器开发者工具的网络面板,确认仅显示1次请求
- 后端(Spring Boot Reactive)记录每个入站请求,日志显示请求被触发2次
- 在Angular发起请求前添加
console.log,仅打印1次请求URL
相关代码
Api Service
export class StudentApiService { public cachedStudent$: Observable<StudentDto>; getStudent(id: string, withParentInfo: boolean): Observable<StudentDto> { const headers = new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': 'Bearer your-token', // Example of adding a token 'Custom-Header': 'custom-value' }); const url = `${this.base_url}/by-id/${id}?withParentInfo=${withParentInfo}`; if (!this.cachedStudent$) { this.cachedStudent$ = this.http.get<StudentDto>(url, { headers }).pipe( take(1), retry(1), shareReplay(1) ) } return this.cachedStudent$; } }
Component Class
export class AddEditStudentComponent implements OnInit, OnDestroy { private sub = new Subscription(); studentId: string; constructor( private studentApi: StudentApiService, private activatedRoute: ActivatedRoute, private router: Router ) {} ngOnInit() { console.log('ngOnInit called'); const url = this.activatedRoute.snapshot.url[0].path; this.studentId = this.activatedRoute.snapshot.paramMap.get('studentId'); this.sub.add( this.studentApi.getStudent(this.studentId, false).subscribe({ next: data => { console.log(data); }, error: err => { console.log('Error fetching student data:', err); } }) ); } ngOnDestroy() { this.sub.unsubscribe(); } }
已排查的方向
- 缓存:使用
shareReplay(1)防止重复请求,但问题仍存在 - 路由变更:检查路由重初始化是否导致重复请求,未发现相关问题
- ngOnInit:组件的
ngOnInit()方法仅触发1次,组件未被不必要地重载
内容的提问来源于stack exchange,提问作者Suryansh Sharma
相关产品推荐
相关产品推荐

