1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Angular HttpClient is calling the GET request twice

Discussão em 'Angular' iniciado por Suryansh Sharma, Setembro 27, 2024.

  1. I'm facing an issue where Angular's HttpClient is making a GET request twice, but only one request is visible in the browser's network tab. However, my backend logs show that the GET request is being triggered twice. What I've Tried

    I checked the Network tab in the browser's developer tools, and it shows only one request being fired.

    On the backend (Spring Boot Reactive), I'm logging every incoming request, and I see the request being logged twice.

    I added a console.log in Angular before the request is made, and it only logs the URL once.

    I'm using Angular's HttpClient with a simple GET request that fetches data from the backend. The relevant code is below.


    **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();
    }

    }



    What I've Investigated

    Caching: I have used shareReplay(1) to prevent multiple requests, but the issue persists.

    Route Changes: I've checked to see if the route reinitialization could be causing the request to fire twice, but I don't see any route-related issues.

    ngOnInit: The ngOnInit() method in my component is only triggered once, so it doesn't seem like the component is being reloaded unnecessarily.

    Continue reading...

Compartilhe esta Página