Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - Smart table won't fill

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.

like image 516
Bm8 Avatar asked Mar 14 '26 09:03

Bm8


1 Answers

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.

like image 111
End Avatar answered Mar 16 '26 23:03

End



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!