Angular API data not loading on page refresh unless user triggers interaction

Discussão em 'Angular' iniciado por User03, Agosto 13, 2025.

  1. User03

    User03 Guest

    I have an Angular 20+ application with a route /explore-developers that should load a list of developers from my backend API when the page is opened.

    I have an Angular 16 application with a route /explore-developers that should load a list of developers from my backend API when the page is opened.

    Expected behavior: When I open the page (either by navigation or direct URL) or refresh the page, the data from the API should automatically load and display in the table.

    Actual behavior: When I refresh the page or load it directly, the user cards are empty. The data only appears after I click a filter or trigger another UI event, which re-runs the API call.

    API endpoint https:///api/users/devs?page=0&size=10&minRate=20&maxRate=50

    Relevant component code:

    import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { FormsModule } from '@angular/forms';
    import { RouterModule } from '@angular/router';
    import { ApiService } from '../../services/api.service';

    interface Developer {
    id: number;
    firstName: string;
    country: string;
    experienceLevel: string;
    // other fields...
    }

    @Component({
    selector: 'app-explore-developers',
    standalone: true,
    imports: [CommonModule, FormsModule, RouterModule],
    templateUrl: './explore-developers.component.html',
    styleUrls: ['./explore-developers.component.css']
    })
    export class ExploreDevelopersComponent implements OnInit {
    developers: Developer[] = [];

    constructor(
    private apiService: ApiService,
    private cdRef: ChangeDetectorRef
    ) {}

    ngOnInit(): void {
    this.loadDevelopers();
    }

    loadDevelopers(): void {
    this.apiService.get<any>('api/users/devs?page=0&size=10&minRate=20&maxRate=50')
    .subscribe({
    next: data => {
    this.developers = data.content || [];
    this.cdRef.detectChanges();
    },
    error: err => console.error(err)
    });
    }
    }


    What I’ve tried so far:

    Calling loadDevelopers() in ngOnInit()

    Wrapping the API call in setTimeout() to delay execution

    Using ChangeDetectorRef.detectChanges() after assigning data

    Ensuring the API endpoint works (tested directly in browser, returns data)

    Question: Why is my API call not fetching and displaying data when the page is refreshed or loaded directly, and how can I make the data load automatically on initial page load without requiring user interaction?

    Continue reading...

Compartilhe esta Página