在angularjs工厂使用工厂

时间:2018-05-29 08:01:10

标签: javascript angularjs factory

我有一个角度应用程序,它从不同的API读取一些数据,我写了多个工厂来捕获它们,每个工厂应该使用一个参数来检索工厂提供的数据。像这样的东西:

var eqDetail = angular.module('eqDetail', []);
eqDetail.config(['$locationProvider', function($locationProvider) {
  $locationProvider.html5Mode({
    enabled: true,
    requireBase: false
  });
}]);


eqDetail.factory('eqInfoFactory', function($location, $http) {
  return {
    eqInfo: getEqInfo()

  }

  function getEqInfo() {
    //routines for acquiring data and sanitize data
  });
return tmp // and object contaning sanitized data           
}
});
eqDetail.factory('lastInspectionDetail', ['eqInfoFactory', function($http,
  eqInfoFactory) {
  return {
    insInfo: getInsInfo()
  }

  function getInsInfo() {
    var eq = eqInfoFactory.eqInfo;
    // get second set of data base on 'eq'

    return tmp
  }
}]);


eqDetail.controller('eqInfo', function($scope, eqInfoFactory) {
  $scope.eq = {};
  $scope.eq = eqInfoFactory.eqInfo;
  console.log($scope.eq);

});
eqDetail.controller('inspectionResult', function($scope, lastInspectionDetail) {
  $scope.insResult = lastInspectionDetail.insInfo;
  console.log($scope.insResult)
})

问题是第二家工厂的eqInfoFactory.eqInfo出现了undefined

我是否以正确的方式使用工厂?以及如何将它们注入彼此?

2 个答案:

答案 0 :(得分:1)

Angular的依赖注入需要,如果它与数组符号一起使用(它肯定至少应该为了缩小安全),每个依赖 - 所以你缺少Angular的$http服务:

//should be ['$http', 'eqInfoFactory', fn(x)...]
eqDetail.factory('lastInspectionDetail', ['eqInfoFactory', function($http,
  eqInfoFactory) {
  return {
    insInfo: getInsInfo()
  }

  function getInsInfo() {
    var eq = eqInfoFactory.eqInfo;
    // get second set of data base on 'eq'

    return tmp
  }
}]);

答案 1 :(得分:0)

您需要通过将$ http添加到缩小列表来修复此行:

eqDetail.factory('lastInspectionDetail', ['eqInfoFactory', function($http,eqInfoFactory) {

更改为此行:

eqDetail.factory('lastInspectionDetail', ['$http','eqInfoFactory', function($http,eqInfoFactory) {