2016-09-21 63 views
0

我有2个工厂:ApiService和LocationService。角度工厂依赖问题

在ApiService中,我想从LocationService将使用的$ http调用中返回端点。

但是,似乎控制器调用LocationService时,它不会等待来自ApiService的响应。下面是一些代码片段,在ApiService当我终于得到它的工作我会缓存,所以我不会需要将每一次服务器调用来获取端点:

services.factory("ApiService", ["$location", "$http", function ($location, $http) { 
    return { 
     getEndpointUrl: function() { 
      var endpoint; 

      $http({ 
       method: 'GET', 
       url: '/site/apiendpoint' 
      }).then(function successCallback(response) { 
       endpoint = response.data; 
       console.log(endpoint); 
       return endpoint; 
      }, function errorCallback(response) { 
       console.error('Error retrieving API endpoint'); 
      }); 
     } 
    } 
}]); 

这里是位置服务,它消耗ApiService:

services.factory("LocationService", ["$resource", "ApiService", function ($resource, apiService) { 
    var baseUri = apiService.getEndpointUrl(); 
    return $resource(baseUri + '/location', {}, { 
     usStates: { method: 'GET', url: baseUri + '/location/us/states' } 
    }); 
}]); 

当我的控制器试图调用LocationService.usStates的基本URI是不确定的。我在这里做错了什么?

回答

2

的原因是因为你的getEndpointUrl功能是异步的,它没有返回值。

由于您的LocationService使用$资源,并依赖于baseUri,我建议引导与初始的页面加载,使之恒等一起数据:

angular.module('yourModule').constant('baseUrl', window.baseUrl); 

那么你的服务将其注入到创建您的资源:

services.factory("LocationService", ["$resource", "ApiService", "baseUrl", function ($resource, apiService, baseUrl) { 
     return $resource(baseUrl + '/location', {}, { 
      usStates: { method: 'GET', url: baseUrl + '/location/us/states' } 
     }); 
    }]); 
+0

嗨,这将是完美的,但我该如何设置该动态的第一次?由于我必须从另一个端点获取端点,因此如果这有意义,那么每个环境的该端点可能会有所不同。 – TheWebGuy

+0

您使用哪种服务器端技术? – DerekMT12

+0

.NET MVC(返回API endpoing)和另一个Web API 2项目(即端点)。我最初的想法是根据它们所在的位置(location.host())设置端点,但我正在寻找更清洁的东西,我在web.config中设置了该设置。 – TheWebGuy

0

ApiService中,您实际上并没有从getEndpointUrl()返回值。您如何从ApiService返回承诺,然后以LocationService以同步方式使用该承诺?

services.factory("ApiService", ["$location", "$http", function($location, $http) { 
    return { 
     getEndpointUrl: function() { 
      var endpoint; 

      return $http({ 
       method: 'GET', 
       url: '/site/apiendpoint' 
      }); 
     } 
    } 
}]); 

services.factory("LocationService", ["$resource", "ApiService", function($resource, apiService) { 
    return { 
     getLocations: function() { 
      return apiService.getEndpointUrl().then(function successCallback(response) { 
       var baseUri = response.data; 

       return $resource(baseUri + '/location', {}, { 
        usStates: { method: 'GET', url: baseUri + '/location/us/states' } 
       }); 

      }, function errorCallback(response) { 
       console.error('Error retrieving API endpoint'); 
      }); 
     } 
    }; 
}]); 

然后在你的控制器:

LocationService.getLocations().then(function(data) { 
    $scope.statesResult = data.result.states; 
});