0

Sorry, I'm new to webDev. How I can get data from factory to mainCtrl.

Code:

shopApp.controller("mainCtrl",function($scope,newItemsFactory){
    $scope.newItems=newItemsFactory.getNewItems();
    console.log($scope.newItems);  //NOT WORK
});

shopApp.factory('newItemsFactory',function($http){
    return{
        getNewItems:function(){
            $http({method: 'GET', url: '../php/newItems.php'}).
                then (function success(response) {
                       return response.data;
                    }, function error(response) {
                        console.log("Error!");
                    }
                );
        }
    }
});

Thank you)

  • Return promise from factory method, `return $http....` and in controller use `.then()` – Satpal May 06 '17 at 15:48
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Wing May 06 '17 at 17:57

1 Answers1

0

First you should return Promise from newItemsFactory.getNewItems():

getNewItems:function(){
    return $http({method: 'GET', url: '../php/newItems.php'});
}

use Promise.then to deal with the result and Promise.catch to deal with the error in your controller:

$scope.newItems=newItemsFactory.getNewItems().then(function(response) {
    $scope.newItems = response.data;
}.catch(function error(response) {
    console.log("Error!");
};
Pengyy
  • 37,383
  • 15
  • 83
  • 73