I'm trying to access data from the client side using Loopback and the AngularJS SDK (I think my issue is more to do with my, as yet, not great Angular skills). I am trying to pass the with an AngularJS controller which calls a service as show below. This does actually work and the data is shown on my web page with {{theSuppliers}}, however when I look at the console I see the result below.
scope.theSuppliers [$promise: {…}, $resolved: false]
rowdata from within the factory: (3) [Resource, Resource, Resource, $promise: {…}, $resolved: true]
Clearly I'm doing something wrong and in the end 'm trying to represent the data in a data grid (ag-grid) which doesn't accept the data. I've been looking at it now for days and now going around in circles.
angular.module('supplierModule', ['lbServices', 'dataServices'])
.controller('SupplierListController',
function ($scope, $log, dbService) {
$scope.theSuppliers = dbService.getAllSuppliers();
$log.log('$scope.theSuppliers', $scope.theSuppliers);
});
angular.module('dataServices', ['lbServices'])
.service('dbService', function ($log, Supplier) {
var dbSvc = {};
dbSvc.getAllSuppliers = function () {
return Supplier.find(function (mysuppliers) {
$log.log('rowdata from within the factory: ', mysuppliers);
});
};
return dbSvc;
});
BTW, I've tried instantiating the data grid from within a function that calls Supplier.find() and it works - as per below. But not ideal as I want to be able to call the service from other places in my code.
var rowData = Supplier.find(function (mysuppliers) {
...
var gridOptions = {
columnDefs: columnDefs,
rowData: rowData,
enableSorting: true,
enableFilter: true
};
new agGrid.Grid(eGridDiv, gridOptions);
...
You have to wait for the promise the be resolved.
angular.module('supplierModule', ['lbServices', 'dataServices'])
.controller('SupplierListController',
function ($scope, $log, dbService) {
dbService.getAllSuppliers()
.then(function(suppliers) {
$scope.theSuppliers = suppliers;
});
$log.log('$scope.theSuppliers', $scope.theSuppliers);
});
And you have to use promises to resolve your result from the service:
.service('dbService', function ($log, Supplier) {
var dbSvc = {};
dbSvc.getAllSuppliers = function () {
return new $q(function(resolve) {
Supplier.find(function (mysuppliers) {
$log.log('rowdata from within the factory: ', mysuppliers);
resolve(mysuppliers);
});
})
};
return dbSvc;
});