1

I am trying to handle restangular calls entirely from a service to keep the controller light, and also so I can manipulate the data further within the service later.

Struggling with promises, which I think is my issue. If I can avoid it, I dont want the service to return the promise, and then use .then() in the controller.

If I make the restangular call directly from the controller it works fine.

angular.module('vehicle', ['restangular'])
  .config(
    function(RestangularProvider) {
      RestangularProvider.setBaseUrl('https://jsonplaceholder.typicode.com/');

      RestangularProvider.setResponseExtractor(function(response, operation, what) {
        if (operation === 'getList' && !Array.isArray(response)) {
          return [response];
        }
        return response;
      });
    })
  .controller('VehicleController', function($scope, VehicleService, Restangular) {
    $scope.vehicles = VehicleService.getVehicles();

    Restangular.all('posts').getList().then(function(vehicle) {
      $scope.moreVehicles = vehicle.plain();
    });

  })
  .service('VehicleService', function(Restangular) {
    VehicleService = {};

    VehicleService.vehicles = [];

    VehicleService.getVehicles = function() {
      Restangular.all('posts').getList().then(function(vehicle) {
        VehicleService.vehicles = vehicle.plain();

        return VehicleService.vehicles;
      });
    }

    return VehicleService;
  });

https://plnkr.co/edit/q1cNw6gN12pKsiPaD1o0?p=preview

Any ideas why my combination of service and promise wont return the data to scope?

Horse
  • 3,023
  • 5
  • 38
  • 65
  • No, it's asynchronous - you cannot avoid promises – Bergi Oct 05 '16 at 12:39
  • You're only `return`ing inside the promise `then` callback, but you're not actually `return`ing the promise from the `getVehicles` method. – Bergi Oct 05 '16 at 12:40
  • So you mean I HAVE to have `.then()` in the controller? Ideally I didn't want to return the promise, as I wanted that response in the service so I could manipulate it further later. Any ideas? – Horse Oct 05 '16 at 12:46
  • Yes. What you are asking for [is impossible](https://stackoverflow.com/q/14220321/1048572). You still can manipulate it in the `then` callback. – Bergi Oct 05 '16 at 12:53
  • I'm not necessarily trying to avoid the promise, I get its asynchronous. I just want the promise handled in the service. So the controller binds `VehicleService.vehicles` to scope, `getVehicles` is called in the controller, this updates `VehicleService.vehicles` which is reflected in the scope. – Horse Oct 05 '16 at 13:04

0 Answers0