2016-11-02 3 views
0

HTTP 요청의 결과 인 태그에 따라 module.constant를 설정하려고합니다.http 요청의 결과에 따라 AngularJS가 설정됩니다.

다음은 내 프로젝트의 데모 코드입니다.

code in app.js 

(function(){ 
    var myApp = angular.module('myApp',['ui.router','ui.bootstrap']); 

    myApp.contant("API_URL","https://www.helloworld.com/API"); 

    myApp.run(function($rootScope.$http){ 
    some code; 
    }); 
})(); 

다음과 같은 HTTP 요청의 결과에 따라 특별한 ID를 설정하고 싶습니다.

$http.get(API_URL + "/configTag") 
    .then(function success(response){ 
     var tag = response.data.tag; 
     if(tag === 0) { 
     myApp.constant("specialID","111111111"); 
     } else if (tag === 1) { 
     myApp.constant("specialID","222222222"); 
     } else { 
     myApp.constant("specialID","333333333"); 
     } 
    },function error(response){ 

    }); 

하지만 저는 프런트 엔드와 AngularJS에 익숙하지 않습니다. 이걸 어떻게 깨닫는 지 모르겠다.

+0

어떤 오류가 발생합니까? –

+3

일반적인 방법으로 이렇게하는 것은 어렵습니다. $ http를 사용하는 것은 응용 프로그램이 실행되기 전까지는 실제로 사용할 수 없기 때문에 어렵지만 그 시점에서 상수를 설정하기에는 너무 늦습니다. 값을 상수에 저장해야하는 이유는 무엇입니까? 더 간단한 해결책은 상수를 노출시키는 캐시 된 약속을 반환하는 서비스를 갖는 것입니다. – pgreen2

+0

@ShashankAgrawal myApp.run에 코드를 넣으려고했는데 상수를 전역 적으로 사용하는 경우 주입 오류가 –

답변

1

짧은 대답 : $http 서비스를 사용하여 각도 상수를 생성 할 수 없습니다.

AngularJS 프레임 워크는 "구성"단계와 "실행"단계의 두 단계로 작동합니다. "실행"단계가 시작되면 공급자를 더 이상 구성 할 수 없으며 상수를 더 이상 추가 할 수 없습니다. $http 서비스 작업은 "실행"단계에서만 수행 할 수 있습니다.

app.factory("specialIDpromise", function(API_URL, $http) { 
    var promise = $http.get(API_URL + "/configTag") 
     .then(function success(response){ 
      var tag = response.data.tag; 
      if(tag === 0) { 
       //return to chain data 
       return "111111111"; 
      } else if (tag === 1) { 
       return "222222222"; 
      } else { 
       return "333333333"; 
      }; 
     }).catch(function error(response){ 
      //return converts rejection to success 
      return "something"; 
     }); 
    //return promise to factory 
    return promise; 
}); 

가 컨트롤러에 사용하려면, 다음 config 위상

app.controller("myCtrl", function(specialIDpromise) { 
    specialIDpromise.then(function(specialID) { 
     console.log(specialID); 
     //Do other things that depend on specialID 
    }); 
}); 

모든 동작이 동기해야 (상수를 추가하는 등, 서비스 제공자는 상수의 가능성을 제공하지만

AnglerJS 앱의 run 단계에서 $http 서비스로 XHR과 같은 비동기 작업이 발생합니다.