1

I'm looking for a way to change the return of a factory. For example i have an angular project which contains : one controller and one service (factory).

The controller as two Object ("item" and "someItem"). The service expose two methods ("getIem()" and "getSomeItem()").

The object in the controller receive data from the service.

I would like to have the method "getItem()" that return the data present in my json file as an object, and have my method "getSomeItem()" that return a specific item relative to the parameter of the method.

(set the "someItem" object in the controller from the "item" object is a solution, but i want to do that in the "getSomeItem()" methods, perhaps I misunderstood the way promise works, but I thought I could edit the return of the methods in my factory, is that a bad use of a factory ?)

The plunker is here : https://plnkr.co/edit/YGNy92ewINRSAILs83PS?p=preview

var controllers = angular.module('controllers',[]);
var services = angular.module('services',[]);
var app = angular.module('app',['controllers','services']);

controllers.controller('mainController',['myFactory',function(myFactory){

  var vm = this;
  //////////////

  vm.item = {};
  vm.someItem = {};
  activate();

  function activate(){

    myFactory.getItem().then(function(data){
      vm.item = data;
      return vm.item;
    });

    myFactory.getSomeItem(0).then(function(data){
      vm.someItem = data;
      return vm.someItem;
    });
  }

}]);

services.factory('myFactory',['$http', function($http){

  var getItem = function(){
    return $http.get('myData.json')
    .success(function(data){return data})
    .error(function(data){throw new Error(data + status + headers + config)})
  };

  var getSomeItem = function(item){
    return $http.get('myData.json')
    .success(function(data){
      //I try to return just a specific object 
      var oneObject = data.data.objet1[item]; 
      return oneObject})
    .error(function(data){throw new Error(data + status + headers + config)})
  };

  return{
    getItem : getItem,
    getSomeItem : getSomeItem
  }

}]);
vince4128
  • 61
  • 4

1 Answers1

0

The problem lies in your .success and .error, if you change it a .then it should work:

.then(
    function(data){
        //I try to return just a specific object 
        var oneObject = data.data.objet1[item]; 
        return oneObject
    },
    function(data){
        throw new Error(data + status + headers + config)
    }
 );

Updated plunkr: https://plnkr.co/edit/19naxd7wWr9JNuQkbViS?p=preview

explanation here: Angular HttpPromise: difference between `success`/`error` methods and `then`'s arguments

Community
  • 1
  • 1
Martijn Welker
  • 5,575
  • 1
  • 16
  • 26
  • the explanation of the difference between 'success'/'error' and 'then' is very helpfull ! thanks a lot Martin! – vince4128 Jan 20 '16 at 11:32