0

Trying to set up Angular factory/service to consume API data, so I can build default index and show pages.

My problem is that data not returned from factory to controller and view.

My second issue is when I click on customer it should query API again and return concerned customer. However I'm mixed up on how to pass customerID through routeParams

app.factory('apiFactory', ["$http", "$routeParams", ($http, $routeParams) ->
  factory = {}

  factory.getCustomers = ->
    $http(
      method: "GET"
      url: "/customers.json"
    ).success( (data) ->
      data
    ).error( (status) ->
      console.log "Error"

  factory.getCustomer = (customerId) ->
    customerId = $routeParams.customerID
    customer

  factory
])

app.controller("CustomersController", ["$scope", "apiFactory", ($scope, apiFactory) ->
  $scope.customers = apiFactory.getCustomers()
  console.log $scope.customers

  $scope.customer = apiFactory.getCustomer
  console.log $scope.customer
])

In the following sample I replaced url by static json file but no luck either. Here is corresponding Plunker http://plnkr.co/edit/G6eFwR7uCNu32cLa1MvV?p=preview

olimart
  • 1,529
  • 3
  • 17
  • 32
  • You might take a look at my answer here: http://stackoverflow.com/questions/16930473/angularjs-factory-http-get-json-file/16931623#16931623 – Karen Zilles Mar 31 '14 at 20:39

2 Answers2

0

I'm no coffeescript expert but it looks like your getCustomers function is returning a promise. So you would need to call it like this:

apiFactory.getCustomers().success( (data) ->
    $scope.customers = data);

The success handler you are using in getCustomers() isn't really doing anything as nothing is using its return value.

If you want to prevent the controller from loading until after the http request returns then you will need to set it up in the routing using resolve.

rob
  • 17,995
  • 12
  • 69
  • 94
0

The correct way would be to use .then()

factory.getCustomers = ->
$http(
  method: "GET"
  url: "/customers.json"
).then( (data) ->
  data;
).error( (status) ->
  console.log "Error"

And in your controller:

apiFactory.getCustomers().then(function(data) ->
    $scope.customers = data
);

.then allows you to return your promise and work with it!

tymeJV
  • 103,943
  • 14
  • 161
  • 157