AngularJS 在返回之前解决承诺



下午好,

我是 angularJS 的新手,如果我问一个基本问题,很抱歉...... 但我有一个问题:

我有一个从配置中获取字符串的服务 (Service2),我有另一个服务(Service1),它使用此服务2 执行更多操作并返回一个 URL(返回服务2 + 服务1上的操作)... 但是,在函数初始化()中,它跳过了

Service2.getConfig().then(function (config) {
baseUrl = config.endPointUrl;
});

然后直接返回。获取不完整的 URL 我需要什么... 对于如何在从 service2 完成所有操作后才让它返回服务1,您有什么建议吗?

这是我正在尝试执行的基本代码

服务 1

function Service1($resource, Service2) {
var resourceUrl = "";
var baseUrl = "";
initialize();
function initialize() {
Service2.getConfig().then(function (config) {
baseUrl = config.endPointUrl;
});
resourceUrl = baseUrl + "/event/history/period";
}
return $resource(resourceUrl, {}, {
'query': { method: 'GET', isArray: true }
});
}

服务2

function service2($resource, $log) {
var configService = {};
configService.getConfig = getConfigFromServer;
return configService;
function getConfigFromServer() {
var eventDataResource = $resource('api/service-config');
return eventDataResource.get().$promise;
}
}

只有在获得数据后才需要返回。getConfig()似乎是异步调用。因此,将返回移动到.then回调是最简单的操作:

function Service1($resource, Service2) {
var resourceUrl = "";
var baseUrl = "";
Service2.getConfig().then(function (config) {
baseUrl = config.endPointUrl;
resourceUrl = baseUrl + "/event/history/period";
return $resource(resourceUrl, {}, {
'query': { method: 'GET', isArray: true }
});
});
}

有关更多信息:承诺、.then()

搜索更多并向其他人询问此问题,我使用$http找到以下解决方案

function Service1(Service2, $http, $q) {
var eventDataService = {};
var endPointUrl = $q.defer();
Service2.getConfig().then(function (config) {
endPointUrl.resolve(config.endPointUrl);
});
eventDataService.getCount = getCount;
return eventDataService;
function getEndPointUrl() {
return endPointUrl.promise;
}
function getCount(successCallback, failureCallback) {
getEndPointUrl().then(function (endPointUrl) {
var uri = endPointUrl + '/event/gunshotCount';
$http.get(uri).then(function (data) {
successCallback(data);
}, function (error) {
failureCallback(error);
});
})
.catch(function (error) {
$log.error("Error while getting REST endpoint Url. Error : " + error);
});
}
}

谢谢大家!!现在我对承诺:D有了更多的了解

最新更新