Angular HttpClient 调用 GET 请求两次

问题描述 投票:0回答:1

我遇到一个问题,Angular 的 HttpClient 发出两次 GET 请求,但在浏览器的网络选项卡中只有一个请求可见。但是,我的后端日志显示 GET 请求被触发两次。 我尝试过的事情

我检查了浏览器开发者工具中的“网络”选项卡,它显示仅触发了一个请求。

在后端(Spring Boot Reactive),我正在记录每个传入请求,并且我看到该请求被记录了两次。

我在发出请求之前在 Angular 中添加了一个 console.log,它只记录 URL 一次。

我使用 Angular 的 HttpClient 和一个简单的 GET 请求来从后端获取数据。相关代码如下。


**This is my Api Service.**

export class StudentApiService {
  public cachedStudent$: Observable<StudentDto>;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$;
} 
}

**This is my Component Class**

export class AddEditStudentComponent implements OnInit,OnDestroy {

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');
      // Subscribe to the Subject's observable
      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() 方法仅触发一次,因此组件似乎没有不必要地重新加载。

angular typescript rxjs angular-httpclient
1个回答
0
投票

可能有两个原因:

1-可能您启用了 ssr 设置,并且您正在尝试使用 jwt 令牌调用 http 请求,但服务器和服务器响应中没有 jwt 令牌,状态为 401。因此,在客户端中,由于服务器中的错误,您再次调用http请求。

2-你的网络服务器配置做到了这一点。

© www.soinside.com 2019 - 2024. All rights reserved.