gpt4 book ai didi

javascript - 如何设计服务来获取需要多次调用的数据?

转载 作者:行者123 更新时间:2023-12-03 05:22:08 25 4
gpt4 key购买 nike

我有一个返回 promise 服务

function GetSuggestedPeersService($http, SITE_CONFIG) {
var getSuggestedPeersService = this;

var data;

getSuggestedPeersService.getSuggestedPeersList = function() {
var baseUrl = SITE_CONFIG.baseUrl + "fetchSuggestedPeers";
var response = $http({
method : 'POST',
url : baseUrl,
headers : {
'Content-Type' : 'application/x-www-form-urlencoded'
},
data : data
});
return response;
}

getSuggestedPeersService.setSuggestedPeers = function(suggestedPeers) {
getSuggestedPeersService.suggestedPeers = suggestedPeers;
}

getSuggestedPeersService.getSuggestedPeers = function() {
return getSuggestedPeersService.suggestedPeers;
}

}

现在我在 Controller 中使用以下内容来解决 promise :

//gets the suggested peers
var promiseSuggestedPeers = GetSuggestedPeersService.getSuggestedPeersList();
promiseSuggestedPeers.then(function (response) {
peerHealthController.GetSuggPeersShow = response.data;
GetSuggestedPeersService.setSuggestedPeers(peerHealthController.GetSuggPeersShow);

return peerHealthController.GetSuggPeersShow;
})
.catch(function (error) {
console.log("Something went terribly wrong Suggested Peers.");
});

现在我的问题是多次调用此服务,并且还需要在其他服务调用上更新此服务。

编写 Controller 部分的最佳方法是什么,以免每次调用服务时都重复解析 promise ?

最佳答案

好久不见了。

但我只是想回答这个问题。

设计这个的最好方法是使用工厂。所以这将成为一个可重用的服务。

示例代码如下:

var httpMethods = peerHealthApp.factory('HttpService',HttpService);

httpMethods.$inject = ['$http', 'SITE_CONFIG'];

function HttpService($http, SITE_CONFIG){
console.log("SITE_CONFIG from Peer Service: " + SITE_CONFIG);
var factory = {
httpGet : function(relativePath,data){
var baseUrl = SITE_CONFIG.baseUrl + relativePath;
var response = $http({
method : 'GET',
url : baseUrl,
headers : {
'Content-Type' : 'application/x-www-form-urlencoded'
},
data : data
});
return response;

},
httpPost : function(relativePath, data){
var baseUrl = SITE_CONFIG.baseUrl + relativePath;
var response = $http({
method : 'POST',
url : baseUrl,
headers : {
'Content-Type' : 'application/x-www-form-urlencoded'
},
data : data
});
return response;
}

};


return factory;

}

上面的内容可以像下面这样反复使用:

var data=$.param({
"url":moderatedArticleLink
});
var promiseURLMetaData = HttpService.httpPost("parseUrlMetadata", data);
promiseURLMetaData.then(function (response) {
var urlMetaData = response.data;
return urlMetaData;
})
.catch(function (error) {
console.log("Something went terribly wrong while trying to get URL Meta Data.");
});

关于javascript - 如何设计服务来获取需要多次调用的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41330760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com