2014-02-22 102 views
1

我有一个工厂函数,它不会返回我想在控制器中设置的变量。虽然我没有收到错误,但只是变量不会被设置为它所设想的值。返回空对象的服务函数

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 
    } 
}); 
+0

它看起来像你检查你的变量之前的承诺已得到解决。 –

+0

我试着在.then函数中放入返回值,但那也不起作用。 – Batman

回答

0

尝试链接你的承诺是这样的:

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){ 

}); 
0

您遇到的问题是您正在使用承诺。当您将console.log放在then()函数之外时,您在之前记录变量它实际上已被解决。

如果您将console.log放入您的then()函数(在分配站点地图后),它应该显示正确的值,但您仍然无法可靠地访问它。

我想为你后访问siteMap价值已经填充了数据最简单的方法是在一个回调函数来传递。例如:

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

    $().SPServices({ 
     operation: "GetAllSubWebCollection", 
     async: true 
    }).then(function(response){ 
     // Process the data and set siteMap 
     // ... 
     siteMap = map; 

     // now pass siteMap to the callback 
     _callback(siteMap); 
    }); 

你会那么在你的控制器使用像这样:

SiteService.getSiteMap(function(sitemap){ 
    // Do something with your sitemap here 
}); 

现在,虽然这会工作,它只是一个简单的例子,而不一定是最好的方式。如果您不喜欢回叫,则可以创建第二个承诺,仅在分配siteMap时才能解决。同样取决于您的使用案例getSiteMap(),您可能需要缓存该值,否则每次都会调用该请求。