My Smart table won't fill using HttpClient to send a get request to get json data.
this.http.get('http://localhost:56591/api/db/get').subscribe((data) => {
return data;
});
This returns:
[
{"id":1,"name":"User1","email":"[email protected]","password":"test"},
{"id":2,"name":"User2","email":"[email protected]","password":"test"},
{"id":3,"name":"User3","email":"[email protected]","password":"test"}
]
Using the return in subscribe gives me this error:
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)
While assigning the object directly to a variable is working:
var data = [
{"id":1,"name":"User1","email":"[email protected]","password":"test"},
{"id":2,"name":"User2","email":"[email protected]","password":"test"},
{"id":3,"name":"User3","email":"[email protected]","password":"test"}
];
return data;
The only difference I can find is that this code gives an error when using the get request instead of directly assigning a variable to the object..
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[]'.
Does anyone know where I went wrong?
Thanks in advance.
You have to wait for the Http request to complete before you can assign the data that it returns. So what is happening when you assign const data = this.service.getData();
nothing is being returned.
You can solve this by returning an Observable from your http call in your service:
getData() {
return this.http.get('http://localhost:56591/api/db/get');
}
Then in your component subscribe to the returned Observable, this will wait for the http call to resolve before passing the data into this.source.load(data);
this.service.getData().subscribe((data) => {
this.source.load(data);
});
Let me know if that works, otherwise we can troubleshoot further.