"Angular HttpClient data inconsistency after page refresh: duplicate or missing entries in...

Discussão em 'Angular' iniciado por Newbie, Novembro 14, 2024.

  1. Newbie

    Newbie Guest

    I'm working on an Angular project where I display a list of tables at the top of the page. When I click on a table name, I use Angular's HttpClient and ActivatedRoute to fetch the selected table's details based on the id parameter in the route. However, after refreshing the page, the list of table names at the top sometimes loads inconsistently: sometimes it shows duplicates, sometimes all entries are missing, and sometimes it loads correctly.

    Loaded table name twice, (after refresh)

    No Table name

    My Service class:

    getTables(): Observable<Table[]> {
    return this._http.get<Table[]>(`${this.apiUrl}/GetTableDescriptors`)
    .pipe(
    catchError(error => {
    console.error(this.handleError(error));
    return throwError(() => new Error('Error geting tables!'));
    })
    );
    };

    getCurrentTable(_tableID: string): Observable<Table> {
    return this._http.get<Table>(`${this.apiUrl}/Table/${_tableID}`)
    .pipe(
    catchError(error => {
    console.error(this.handleError(error));
    return throwError(() => new Error("Error getting table with an id {_tableID}"));
    })
    );
    };


    App Routes ts file:

    export const routes: Routes = [
    {path: 'home', component: HomeComponent},
    {path: 'table/:id', component: TableComponent},
    {path: '', redirectTo: '/home', pathMatch: 'full'},
    {path: '**', component: PageNotFoundComponent}
    ];


    @NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
    })


    App component:

    <app-page-header></app-page-header>


    Page Header Component:

    export class PageHeaderComponent implements OnInit{
    tables: Table[] = [];

    constructor(
    private _tableService: TableService) { }

    ngOnInit() {
    this.getTables();
    }

    getTables() {
    this.tables = [];
    this._tableService.getTables().subscribe((_tablesFromAPI: Table[]) => {
    this.tables = _tablesFromAPI;
    });
    }
    }


    <ul>
    <li>
    <a routerLink="/home" [routerLinkActive]="['active']">Start</a>
    <ng-container *ngFor="let table of tables; let i = index">
    <a
    [routerLink]="'/table/' + table.id"
    [routerLinkActive]="['active']"
    >
    {{table.name}}
    </a>
    </ng-container>
    </li>
    </ul>

    <router-outlet></router-outlet>


    Table Component:

    export class TableComponent implements OnInit, AfterViewInit, OnDestroy {

    currentTable: Table;

    constructor(private _activatedRoute: ActivatedRoute) {}

    ngOnInit(): void {
    this.paramMapSubscription = this._activatedRoute.paramMap.subscribe((_activateRoute: ParamMap) => {
    this.tableIndex = _activateRoute.get('id');
    try {
    this._tableService.getCurrentTable(this.tableIndex).subscribe( {
    next: (_tableFromServer: Table) => {
    this.currentTable = _tableFromServer;
    },
    error: err => console.log('error: ',err)
    })
    } catch (error) {
    console.error("Error:", error);
    }
    });
    }

    ngOnDestroy(): void {
    if (this.paramMapSubscription) {
    this.paramMapSubscription.unsubscribe();
    }
    }
    }


    I have tried:

    • Using the async pipe in the template to manage subscriptions.
    • Checking for potential redundant subscriptions or lifecycle issues.

    How can I ensure that the table names are loaded consistently without duplicates or missing entries after a page refresh? Is there a better approach to managing data caching and navigation state in this setup? Thanks

    Continue reading...

Compartilhe esta Página