为什么我没有从angularJS的工厂函数中得到响应[重复]

时间:2022-08-15 16:55:51

This question already has an answer here:

这个问题已经有了答案:

I got this angular factory:

我得到了这个角工厂:

var productApp = angular.module('productApp', ['ngRoute', 'LocalStorageModule', 'angularSlideables', 'ui.bootstrap']);

productApp.factory('productFactory', function($http, localStorageService, $q) {
    var factory = {};

    factory.getProductById = function(prod_id) {        
        if(prod_id !== '') {
            $http({
                url: 'rest/message/getProductById/' + prod_id,
                method: 'GET'
            }).success(function(data, status) {
                return data;
            }).error(function(data, status){
                // do nothing
            });
        }else {
            alert("There was an error while passing the ID. Please refresh the page and try again");
        }       
    }

    return factory;
});

Injecting the factory in a controller and calling to the "getProductById" function:

在控制器中注入工厂并调用“getProductById”函数:

productApp.controller('ModalInstanceCtrl', function ($scope, $modalInstance, productFactory, prodId) {  
  console.log("this is the prod id " + prodId);
  // search product in the database
  $scope.prod = productFactory.getProductById(prodId);
  console.log($scope.prod);
  $scope.ok = function () {
      console.log($scope.prodData);
  };

  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };
});

Now, don't know what's wrong with it... the function RETURNS the data because i did a console.log(data) and saw all the response, but in the controller if i inspect the $scope.prod, it's undefined. It's not returning the data back from the function.

现在,不知道是怎么回事……函数返回数据,因为我执行了一个console.log(数据)并看到了所有的响应,但是在控制器中如果我检查$scope。刺激,这是未定义的。它不会从函数返回数据。

(Just in case you guys ask, the "prodId" in the controller parameter is fine, and retrieving that from another controller)

(以防你们问,控制器参数中的“prodId”很好,从另一个控制器中检索它)

How can i solve this? :(

我怎么解决这个问题呢?:(

Thanks in advance.

提前谢谢。

2 个解决方案

#1


1  

The pattern I have used to solve this problem is to pass in the success & error callback functions to the factory... like this:

我用来解决这个问题的模式是将成功和错误回调函数传递给工厂。是这样的:

var productApp = angular.module('productApp', ['ngRoute', 'LocalStorageModule', 'angularSlideables', 'ui.bootstrap']);

productApp.factory('productFactory', function($http, localStorageService, $q) {
    var factory = {};

    factory.getProductById = function(prod_id, successCallback, errorCallback) {        
        if(prod_id !== '') {
            $http({
                url: 'rest/message/getProductById/' + prod_id,
                method: 'GET'
            })
            .success(successCallback)
            .error(errroCallback);
        } else {
            alert("There was an error while passing the ID. Please refresh the page and try again");
        }       
    }

    return factory;
});

and then:

然后:

productApp.controller('ModalInstanceCtrl', function ($scope, $modalInstance, productFactory, prodId) {  
  console.log("this is the prod id " + prodId);
  // search product in the database
  productFactory.getProductById(prodId, function successCallback(data) {
         $scope.prod = data;
      }, function errorCallback(data, status) {
         alert("An error occurred retrieving product. Please refresh the page & try again.");
      });
  console.log($scope.prod);

  $scope.ok = function () {
      console.log($scope.prodData);
  };

  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };
});

By doing it this way instead, you have access to the scope in the controller & can do whatever you need to with the returned data.

通过这样做,您可以访问控制器中的范围,并可以对返回的数据执行任何您需要的操作。

#2


1  

Here's what I do. I'm using $resournce instead of $http, but it should be enough to get you going. You may even want to use the $resource since it has the built in fns.

这是我所做的。我使用的是$resournce而不是$http,但是它应该足够让您继续使用。您甚至可能想要使用$resource,因为它有内置fns。

My factory:

我的工厂:

.factory('WorkOrder', function($resource){

    // $resource Usage: $resource(url[, paramDefaults][, actions]);
    return $resource('/controller/get/:id.json', {}, {
        /*
         * By default, the following actions are returned; modify or add as needed
         * { 'get':    {method:'GET'},
         *   'save':   {method:'POST'},
         *   'query':  {method:'GET', isArray:true},
         *   'delete': {method:'DELETE'} };
         */
    });

})

My controller:

我的控制器:

    // get the work order data using the work order id from the tag attribute
var getWO = function() {

    WorkOrder.get({woId:$attrs.id},

        // success callback
        function(response) {
            // Assign the work order data to the scope
            $scope.WorkOrder            = response.WorkOrder;
        },

        // fail callback
        function(response) {
            // whatever...
        }
    );
};
getWO();

I put my success and fail fns in my controller because that's where I most likely know how I want to respond to success or failed calls. I also assign the function to a variable and then call it right after in case I want to include the fn call inside a $timeout or call it elsewhere.

我把我的成功和失败的fns放在我的控制器里,因为这是我最有可能知道我想如何回应成功或失败的电话的地方。我还将函数赋给一个变量,然后调用它,以防我想在$timeout中包含fn调用,或者在其他地方调用它。

Hope this answers your question.

希望这能回答你的问题。

#1


1  

The pattern I have used to solve this problem is to pass in the success & error callback functions to the factory... like this:

我用来解决这个问题的模式是将成功和错误回调函数传递给工厂。是这样的:

var productApp = angular.module('productApp', ['ngRoute', 'LocalStorageModule', 'angularSlideables', 'ui.bootstrap']);

productApp.factory('productFactory', function($http, localStorageService, $q) {
    var factory = {};

    factory.getProductById = function(prod_id, successCallback, errorCallback) {        
        if(prod_id !== '') {
            $http({
                url: 'rest/message/getProductById/' + prod_id,
                method: 'GET'
            })
            .success(successCallback)
            .error(errroCallback);
        } else {
            alert("There was an error while passing the ID. Please refresh the page and try again");
        }       
    }

    return factory;
});

and then:

然后:

productApp.controller('ModalInstanceCtrl', function ($scope, $modalInstance, productFactory, prodId) {  
  console.log("this is the prod id " + prodId);
  // search product in the database
  productFactory.getProductById(prodId, function successCallback(data) {
         $scope.prod = data;
      }, function errorCallback(data, status) {
         alert("An error occurred retrieving product. Please refresh the page & try again.");
      });
  console.log($scope.prod);

  $scope.ok = function () {
      console.log($scope.prodData);
  };

  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };
});

By doing it this way instead, you have access to the scope in the controller & can do whatever you need to with the returned data.

通过这样做,您可以访问控制器中的范围,并可以对返回的数据执行任何您需要的操作。

#2


1  

Here's what I do. I'm using $resournce instead of $http, but it should be enough to get you going. You may even want to use the $resource since it has the built in fns.

这是我所做的。我使用的是$resournce而不是$http,但是它应该足够让您继续使用。您甚至可能想要使用$resource,因为它有内置fns。

My factory:

我的工厂:

.factory('WorkOrder', function($resource){

    // $resource Usage: $resource(url[, paramDefaults][, actions]);
    return $resource('/controller/get/:id.json', {}, {
        /*
         * By default, the following actions are returned; modify or add as needed
         * { 'get':    {method:'GET'},
         *   'save':   {method:'POST'},
         *   'query':  {method:'GET', isArray:true},
         *   'delete': {method:'DELETE'} };
         */
    });

})

My controller:

我的控制器:

    // get the work order data using the work order id from the tag attribute
var getWO = function() {

    WorkOrder.get({woId:$attrs.id},

        // success callback
        function(response) {
            // Assign the work order data to the scope
            $scope.WorkOrder            = response.WorkOrder;
        },

        // fail callback
        function(response) {
            // whatever...
        }
    );
};
getWO();

I put my success and fail fns in my controller because that's where I most likely know how I want to respond to success or failed calls. I also assign the function to a variable and then call it right after in case I want to include the fn call inside a $timeout or call it elsewhere.

我把我的成功和失败的fns放在我的控制器里,因为这是我最有可能知道我想如何回应成功或失败的电话的地方。我还将函数赋给一个变量,然后调用它,以防我想在$timeout中包含fn调用,或者在其他地方调用它。

Hope this answers your question.

希望这能回答你的问题。