0

나는 내 angularjs 프로젝트에서 작업합니다. 나는이 서비스를 만든 : 나는 컨트롤러에서 서비스를 호출하는 방법을 여기데이터가 반환 될 때까지 HTTP 서비스 지연 처리

(function() { 
    "use strict"; 

    angular.module("manageItems").factory("manageItemsService", ["$http", "config", manageItemsService]); 

    function manageItemsService($http, config) { 
     var service = { 
      getNewItems: getNewItems, 
     }; 
     return service; 

     function getNewItems(session, mapName) { 
      return $http.get(serviceUrl + 'getNewItems/' + session + "/" + mapName); 
     } 

    } 
})(); 

을 그리고 :

function getNewItems() { 
    manageItemsService.getNewItems(mapguideService.mapName, mapguideService.sessionId).then(function (result) { 
     self.currentItems = result.data; 
    }) 
} 

내가 응답이 반환 동안 지연 서비스를 확인해야합니다.

self.currentItems 속성이 데이터로 채워질 때까지 대기하도록하기 위해 어떻게 서비스 기능을 변경할 수 있습니까?

+1

는 그것은, 예상되는 동작입니다 ?? –

+0

@ PankajParkar 업데이트를 참조하십시오. – Michael

+0

정확한 시나리오는 무엇입니까? –

답변

0

그러면 .thengetNewItems $ http 전화에 걸 수 있습니다. 검색된 응답 데이터를 기반으로 데이터를 반환할지 아니면 다른 서비스 메서드를 호출할지 결정합니다.

function anotherFunction(){ 
    return $http.get(url); 
} 

function getNewItems(session, mapName) { 
    return $http.get(serviceUrl + 'getNewItems/' + session + "/" + mapName).then(function successCallback(response){ 
     var data = response.data; 
     //call another function if data is empty 
     if(!data.length) 
     return anotherFunction(); //make sure another function should return promise 
     return data; 
    }); 
} 
+0

게시물을 보내 주셔서 감사합니다. 전화를 3 번해야하는 경우 어떻게해야합니까? 먼저 비어있는 경우 seci = ond가 비어 있으면 세 번째로 만듭니다. 좋은 사례라고 생각하지 않습니다. – Michael

+2

이렇게하면 원하는대로 처리 할 수 ​​있습니다. 서비스가 응답하기 전에 중간 단계를 처리하십시오. 이러한 시나리오를 사용하는 것은 좋은 방법입니다. 나는 그 나쁜 습관을 생각하지 않는다. (나쁜 상태라고 언급 된 참고 문헌을 발견하면 알려주기 바란다.) –

1

먼저 HTTP 요청은 결과가 반환되는 동안 응용 프로그램을 중지하지 않도록 비동기 적으로 수행됩니다.

두 가지 옵션이 있습니다. 각도 패턴을 사용하여 결과를 처리하려면 메서드를 조정해야하므로 컨트롤러가 아닌 서비스가 연결되도록 콜백 함수를 서비스에 전달해야합니다. 그것은 것 같은 뭔가 :

서비스 :

(function() { 
     "use strict"; 

     angular.module("manageItems").factory("manageItemsService", ["$http", "config", manageItemsService]); 

     function manageItemsService($http, config) { 
      var service = { 
       getNewItems: getNewItems, 
      }; 
      return service; 

      function getNewItems(session, mapName, callback, errorCallback) { 
       $http.get(serviceUrl + 'getNewItems/' + session + "/" + mapName).then(callback, errorCallback);; 
      } 

     } 
    })(); 

컨트롤러 :

function getNewItems() { 
    manageItemsService.getNewItems(mapguideService.mapName, mapguideService.sessionId, function (result) { 
     //this callback will be called asynchronously when the response is available 
     self.currentItems = result.data; 
    }, function(error) { 
     // called asynchronously if an error occurs 
     // or server returns response with an error status. 
    }) 
} 

두 번째 옵션은 완전히 결과가 예상되는 동안 ... 루프를 삽입하지 않는 것이 좋습니다 것입니다 (에 나쁜)

내가 도왔 으면 좋겠다!

+1

[Promise에서 콜백하는 이유는 무엇입니까?] : //stackoverflow.com/questions/35660881/why-are-callbacks-from-promise-then-methods-an-anti-pattern). – georgeawg

0

코드가 수행해야하는 작업은 체인 약속입니다.

getNewItems 기능 체인 방식을 만들려면, 반환 파생 약속 :

function getNewItems() { 
    //vvvv RETURN promise 
    return manageItemsService.getNewItems(mapguideService.mapName, mapguideService.sessionId) 
     .then(function (response) { 
     self.currentItems = response.data; 
     //RETURN value to chain 
     return response.data; 
    }); 
}; 

그런 다음 더 작업 체인에 반환 약속을 사용

getNewItems().then(function(currentItems) { 
    //Evaluate current Items 
    if (ok) { 
     return "DONE"; 
    } else { 
     //RETURN to chain something else 
     return getOtherItems(); 
    }; 
}).then(function(otherItems) { 
    if (otherItems == "DONE") return; 
    //ELSE 
    self.otherItems = otherItems; 
    //Do further chaining 
}); 

.then를 호출하기 때문에 약속의 방법은 새로운 파생 된 약속을 되 돌린다. 약속의 사슬.

약속이 다른 약속으로 해결 될 수 있기 때문에 어떤 길이의 체인과 을 만들 수 있습니다 (해상도를 추가로 연기 함). 언제든지 약속의 해결을 일시 중지/지연 할 수 있습니다. 체인. 이를 통해 강력한 API를 구현할 수 있습니다. 문제는 무엇인가 불구하고

— AngularJS $q Service API Reference - Chaining Promises