gpt4 book ai didi

javascript - 返回空对象的服务函数

转载 作者:行者123 更新时间:2023-11-28 08:30:14 25 4
gpt4 key购买 nike

我有一个工厂函数,它不会返回我试图在 Controller 中设置的变量。但我没有收到错误,只是变量不会设置为它应该设置的值。

spApp.factory('SiteService', function ($q){
var rootUrl = window.location.protocol + "//" + window.location.hostname;
var siteMap;

//returns object containing info about all sites within collection
var getSiteMap = function () {
siteMap = {};

var promise = $().SPServices({
operation: "GetAllSubWebCollection",
async: true
});

promise.then(
function (response){
map = {}; //init the map
var web = $(response).find("Web").map(function () {
return $(this).attr('Url');
});
var webTitle = $(response).find("Web").map(function () {
return $(this).attr('Title');
});

// create map
for (var i = 0; i < web.length; i++) {
var item = web[i],
title = webTitle[i],
parts = item.split('/'),
domain = parts.splice(0, 3).join('/'),
current;

if (!map[domain]) map[domain] = {url:domain, title:title ,children:{}};
current = map[domain].children;

for (var index in parts) {
var part = parts[index];
if (!current[part]) {
current[part] = {url:domain+'/'+parts.slice(0,index+1).join('/'), title:title, children:{}};
}
current = current[part].children;
}
}
siteMap = map;
}, function(reason){
alert('FAILED:' + reason);
})
console.log(siteMap);
return siteMap;
}

return{
getSiteMap:getSiteMap
}
});

最佳答案

尝试像这样链接你的 promise :

var getSiteMap = function () {
siteMap = {};

var promise = $().SPServices({
operation: "GetAllSubWebCollection",
async: true
});

return promise.then(function(response){ //return your promise
// all you code
siteMap = map;

return siteMap; //return a value to another .then in the chain
});
}

像这样使用它:

SiteService.getSiteMap().then(function(siteMap){

});

关于javascript - 返回空对象的服务函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21962305/

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