Angular中无法将Web API服务数据绑定到ng2-smart-table求助
解决ng2-smart-table无法绑定异步获取数据的问题
我一眼就看出你卡在哪了——能拿到数据但没法在表格里展示,核心问题出在异步请求的时序和模板绑定的匹配上,调整这两点就能搞定:
问题根源拆解
- 异步加载的时序错误:你在
constructor里直接调用this.source.load(this.customers),但API请求是异步的,这行代码执行时,customers还是空数组,因为接口的响应还没回来。 - 模板绑定不匹配:ng2-smart-table的
[source]需要接收LocalDataSource类型的实例,但你模板里绑定的是原始的customers数组,这就导致数据没法被表格正确识别。
修复步骤
1. 调整组件的异步数据加载逻辑
把加载数据源的操作放到subscribe的回调里,确保拿到接口返回的数据后再加载到表格:
constructor(private tableDataService: TableDataService){ this.source = new LocalDataSource(); // 把load操作放到subscribe的成功回调里,保证数据已就绪 this.tableDataService.getCustomerData().subscribe( customers => { this.customers = customers; this.source.load(this.customers); }, error => this.errorMessage = <any>error ); }
2. 修改模板的绑定目标
把模板里的[source]="customers"改成[source]="source",匹配你创建的LocalDataSource实例:
<nb-card-body> <ng2-smart-table [settings]="settings" [source]="source" (deleteConfirm)="onDeleteConfirm($event)"> </ng2-smart-table> </nb-card-body>
额外小提示
后续如果需要更新表格数据(比如新增、编辑后),直接调用this.source.load(新数据数组)或者this.source.add(单条新数据)这类LocalDataSource提供的方法即可,表格会自动更新视图,不用手动操作原始数组。
这样调整后,你的表格就能正常渲染从接口获取到的用户数据了。
内容的提问来源于stack exchange,提问作者Shashank S Chandel
相关产品推荐
相关产品推荐

