반응형
자바스크립트, 그리고 AngularJS 에선 가끔 비동기식으로 호출을 할 때가 있다.
이러한 점 때문에 가끔 제대로 데이터가 받아지지 않을 때가 있는데 $q 를 이용하면 해결 할 수 있다.
(웹 페이지가 로딩이 다 되었을 때 서버로부터 값이 그제야 도착하는 경우)
위 방법을 쓰지 않고도 쓸 수 있는 다른 방법이 있지만, $q 를 이용한 방법이 제일 간단한 듯..
ex)
controller: function($scope, $element, $q, service){
var deferred = $q.defer();
this.getTestData = function(id, password){
service.getSession(id, password).success(function(data){
if(data.result == "OK"){
deferred.resolve();
} else{
deferred.reject("ERROR");
};
}).error(function(){
deferred.reject("ERROR");
});
return deferred.promise;
};
},
controllerAS: "sampleCtrl",
link: function(scope, element, attrs, sampleCtrl){
var promise = sampleCtrl.getTestData();
promise.then(function(){
///
};
}
반응형
'Programming > Angular' 카테고리의 다른 글
공백제거하기. (0) | 2017.08.30 |
---|---|
[AngularJS 2] 문자열의 바이트(Byte) 길이 구하기. (0) | 2017.08.30 |