2014-02-22 2 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.logthen() 함수 외부에 배치하면 변수가 실제로 전에 기록됩니다.

console.logthen() 함수에 넣으면 (사이트 맵이 할당 된 후) 올바른 값이 표시되지만 여전히 안정적으로 액세스 할 수는 없습니다.

내가 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()에 따라 값을 캐시 할 수 있습니다. 그렇지 않으면 요청이 매번 호출됩니다. 이처럼 약속을 체인

관련 문제