3

我想根据作为 HTTP 请求结果的标签设置 module.constant。

以下是我项目中的演示代码;

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 的新手。我不知道如何意识到这一点?

4

2 回答 2

2

简短回答:该$http服务不能用于创建 Angular 常量。

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

在控制器中使用:

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

阶段中的所有操作都config需要同步(包括添加常量)。$http服务的 XHR 等异步操作发生在runAngularJS 应用程序的阶段。

于 2016-11-02T15:01:16.320 回答
0

您可以使用服务器端数据来满足您的需求。你必须注入你需要的模块,并运行你的函数来获取 document.ready 函数中的数据。这是我的做法,但我遇到的唯一问题是服务器是否无法访问;那么应用程序不会被引导。我将此代码放在 angular.module 代码之外的 app.js 文件中,因为尚未启动该应用程序,因此它无法在那里工作。

angular.element(document).ready(function () {
    getConstants();
});

//Get constants from server and manually bootstraps application to the DOM
function getConstants() {    
    var initInjector = angular.injector(["ng"]);
    var $http = initInjector.get("$http");

    $http.get('urlThatRetrievesConstants').then(function (result) {

        /*Below I'm setting the constants on the app module and giving them a 
        name, which will be used to reference in whatever modules you will use it 
        in */

        angular.module('appModuleName').constant('constantsName', result.data);

        /*Here I'm bootstrapping the app*/
        angular.bootstrap(document, ["appModuleName"]);   

    }, function (error) {      
  /*Handle server errors from request*/
    });
}
于 2018-04-19T16:46:53.667 回答