我的智能表不会使用 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);
this.service.getData().subscribe((data) => {
this.source.load(data);
});
让我知道这是否有效,否则我们可以进一步解决问题。
关于Angular - 智能表格不会填满,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52186238/