2016-09-21 69 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; 
});