从控制器向服务发送路径,服务将向控制器返回承诺



我有一个服务,它从一个文件(路径由控制器给定)中获取数据并返回promise,然后是另一个使用上一个服务返回的数据创建具有属性的对象的服务。

我的问题是:

  1. getDataService在控制器之前运行,因此它没有从中获取数据的路径=>没有任何返回(错误)

提供程序"GetDataService"必须从$get工厂方法返回一个值。

  1. 我需要保持这种结构,因为我会有更多不同路径的控制器来提供
  2. 我也对其他解决方案持开放态度,但我需要确保在填充模板之前加载了数据。我试着先调用SetProperties服务,并在其中加入getData服务,但仍然是先执行getData.js

获取数据服务

angular.module('myApp').factory('GetDataService',['$http', function($http) {
    var getData = function(path){
        return  $http.get(path).then(function(result) {
            return result.data;
        });
    };
}]);

setProperties服务

angular.module('myApp').service('PageProperties',['$http', function($http) {
    this.setProps = function(page, data) {      
            some code here
        var properties = {
                isCenterActive : isActive_val,
                //header elements
                titleClass : page, 
                title : data.titles[page],
                //footer elements
                leftLink : leftLink_val,
                leftFooterClass: leftLink_val,
                leftTitle: data.titles[leftLink_val],
                centerLink : centerLink_val,
                centerFooterClass: data.titles[centerLink_val],
                centerTitle : centerTitle_val,
                rightLink : rightLink_val,
                rightFooterClass: rightLink_val ,
                rightTitle : data.titles[rightLink_val],            
            }
        return properties;
    }
}]);

控制器

angular.module('myApp', [])
.controller('meniuController', ['$http', '$stateParams', '$scope', 'GetDataService', 'PageProperties', 
            function($http, $stateParams, $scope, GetDataService, PageProperties){      
    var page = "meniu";
    $scope.language = $stateParams.lang;
    var path = '_global/views/services/json/' + $stateParams.lang + '_data.json';
    /*PageProperties.setProps(page, path).then(function(data){
        //some code here
    });*/
    GetDataService.getData(path).then(function(data){
        $scope.props = PageProperties.setProps(page, data);
    }).catch(function(){
        $scope.error = 'Unable to get data';
    });
}])

提前感谢!!

错误表明您的GetDataService提供商(定义为工厂)没有返回任何

angular.module('myApp').factory('GetDataService',['$http', function($http) {
    var getData = function(path){
        return  $http.get(path).then(function(result) {
            return result.data;
        });
    };
    // you need to actually return something
    return { getData: getData };
}]);

然后你可以让你的PageProperties使用GetDataService

angular
   .module('myApp')
   .service('PageProperties',['GetDataService', function(GetDataService) { 
      this.getProperties = function(path) {
         return GetDataService.getData(path).then(/*transform here*/)
      }

最新更新