【问题标题】:Force re-render / refresh table强制重新渲染/刷新表
【发布时间】:2026-01-18 06:45:01
【问题描述】:

在我选择select 选项对新数据源进行 API 调用后 - 我的表呈现出现在获取数据之前,并且他是空的。如果我选择另一个 select 选项,它会向我显示上一个选项的以前数据

试图放置触发器、等待、承诺

ngOnInit() {
    getAllRoutes();
    this.currentRouteControl.valueChanges
      .pipe(takeUntil(this._unsubscribe))
      .subscribe((val: Route) => {
         this.commonCatalogueService.getRouteScheduleByRouteId(val.id)
            .subscribe((data:any) => this.dataSource = data)});
    }

我希望仅在获取数据后才呈现表格。 UPD:选择列表项将在 ngOnInit 中获取,然后添加到数组中。该数组将通过 ngFor 添加到选择选项

<select class="m-r-20" [formControl]="currentRouteControl">
          <option *ngFor="let route of (routes$ | async)" [ngValue]="route.route">{{
            route.route.number
            }}</option>
        </select>

private routesSubject: BehaviorSubject<RouteWrapper[]> = new BehaviorSubject(null);
routes$ = this.routesSubject.asObservable();

getAllRoutes() {
    this.isLoadingResults = true;
    this.commonCatalogueService
      .getRouteWrappers()
      .pipe(takeUntil(this._unsubscribe))
      .subscribe(val => {
        this.routesSubject.next(val);
        this.isLoadingResults = false;
      });
  }

【问题讨论】:

  • 问题可能出在select 控件上。检查val.id 是否与选择同步
  • 您能否详细介绍一下您如何更改选择选项以及这个新组件如何监听该更改?
  • 第一次更改select时,验证网络请求是否发送?
  • @Ethernetz 添加了更多信息

标签: angular typescript


【解决方案1】:

您可以使用 Angular 的 NgIf 控制何时呈现模板,该模板仅在其表达式计算为 true 时才包含模板。

<table *ngIf="dataSource"></table>

现在,上面的表格只会在 dataSource 被定义/有值时呈现,因为 undefined 在 Javascript 中是一个假值。

【讨论】:

  • OP 面临一个问题,即数据源填充了之前的 select 控件选择。你的回答不能解决问题
  • 它会向我显示上一个选择选项的上一个数据源,而不是选择一个
【解决方案2】:

我导入了ChangeDetectorRef,以便在获取数据后立即更新显示的信息,并在分配订阅数据后添加它。

import { ChangeDetectorRef } from '@angular/core';
constructor( private cd: ChangeDetectorRef ){}

this.commonCatalogueService.getRouteScheduleByRouteId(id)
            .subscribe((data:any) => {
                                      this.dataSource = data;
                                      this.cd.detectChanges();
                                      });

【讨论】: