Angular - 智能表格不会填满

标签 angular angular6 smart-table ng2-smart-table

我的智能表不会使用 HttpClient 发送获取请求以获取 json 数据来填充。

this.http.get('http://localhost:56591/api/db/get').subscribe((data) => {
  return data;
});

返回:

[
  {"id":1,"name":"User1","email":"user1@email.com","password":"test"},
  {"id":2,"name":"User2","email":"user@email.com","password":"test"},
  {"id":3,"name":"User3","email":"user@email.com","password":"test"}
]

在订阅中使用返回给我这个错误:

ERROR TypeError: Cannot read property 'slice' of undefined at LocalDataSource.push../node_modules/ng2-smart-table/lib/data-source/local/local.data-source.js.LocalDataSource.getElements (local.data-source.js:71)

虽然将对象直接分配给变量是可行的:

var data = [
  {"id":1,"name":"User1","email":"user1@email.com","password":"test"},
  {"id":2,"name":"User2","email":"user@email.com","password":"test"},
  {"id":3,"name":"User3","email":"user@email.com","password":"test"}
];
return data;

我能找到的唯一区别是这段代码在使用 get 请求而不是直接将变量分配给对象时会出错。

constructor(private service: SmartTableService) {
  const data = this.service.getData();
  this.source.load(data);
}

Argument of type 'void' is not assignable to parameter of type 'any[]'.

谁知道我哪里出错了?

提前致谢。

最佳答案

您必须等待 Http 请求完成,然后才能分配它返回的数据。那么当您分配 const data = this.service.getData(); 时会发生什么,没有任何返回。

您可以通过从服务中的 http 调用返回一个 Observable 来解决此问题:

getData() {
    return this.http.get('http://localhost:56591/api/db/get');
}

然后在您的组件中订阅返回的 Observable,这将在将数据传递到 this.source.load(data);

之前等待 http 调用解析
this.service.getData().subscribe((data) => {
    this.source.load(data);
});

让我知道这是否有效,否则我们可以进一步解决问题。

关于Angular - 智能表格不会填满,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52186238/

相关文章:

javascript - 如何将 Immutable JS 与类型化的 ES6 类一起使用?

javascript - Angular 4组件被选中的复选框

以编程方式触发 Angular Material 触发触摸状态

javascript - 如何在单击按钮时验证输入不保存 0 或小于 0?

angular-material - multiTemplateDataRows,错误 没有when谓词函数时只能有一个默认行

angular - moment().add() 仅适用于文字值

angular6 特性模块延迟加载抛出错误TypeError : undefined is not a function

javascript - Angularjs int 过滤器在智能表中没有正确排序

angularjs - 仅将过滤后的数据导出到 Angular 智能表中的 csv 中

angularjs - 如何使用 Smart-Table 提高 ng-repeat 性能?