为什么我没有从angularJS中的这个工厂函数中得到响应

Why im not getting the response back from this factory function in angularJS

本文关键字:工厂 函数 响应 angularJS 为什么      更新时间:2024-06-05

我得到了这个角度工厂:

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;
});

在控制器中注入工厂并调用"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');
  };
});

现在,不知道它出了什么问题…函数RETURNS数据,因为我做了console.log(data)并看到了所有响应,但在控制器中,如果我检查$scope.prod,它是未定义的。它不会从函数返回数据。

(万一你们问,控制器参数中的"prodId"很好,并从另一个控制器中检索)

如何解决此问题?:(

提前谢谢。

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

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;
});

然后:

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');
  };
});

通过这种方式,您可以访问控制器&可以对返回的数据执行任何需要的操作。

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

我的工厂:

.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'} };
         */
    });
})

我的控制器:

    // 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();

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

希望这能回答你的问题。