【问题标题】:REST call on application init phase and defining constants based on REST call应用程序初始化阶段的 REST 调用并基于 REST 调用定义常量
【发布时间】:2014-11-23 22:27:50
【问题描述】:

我想知道初始化应用程序以从以下位置检索数据的最佳时刻是什么: 1 - 一个 REST 服务 2 - $routeParams 定义应用程序范围的常量。

配置阶段只接受提供者,并且在配置/运行阶段 $routeParams 属性未定义。

这似乎有点朝着正确的方向: Can you pass parameters to an AngularJS controller on creation?

另外:如何在控制器中定义一个常量,这可能吗?

app.controller('MainCtrl', function($scope) { 
   //define app.constant here
}

--编辑:错字

【问题讨论】:

  • Run 在控制器之前的配置之后运行。运行块 - 在创建注入器后执行并用于启动应用程序。

标签: angularjs constants init


【解决方案1】:

在运行阶段,所有提供程序都应该被初始化并正常工作,您可以使用 $http 服务来检索您需要的任何参数。

我很确定 $routeParams 也在运行阶段初始化。

在控制器中定义常量不是一个好习惯(在我看来),如果它们是该控制器独有的,那么它们只是变量,如果您想要真正的应用程序范围的常量,请使用服务,它们就是这样为:)

我知道一种在创建时将参数传递给控制器​​的简单方法,即使用 angular ui 路由器项目:https://github.com/angular-ui/ui-router

在 resolve 函数中,您可以在必要时进行 http 调用、注入常量等,这非常方便,而且我个人从来不会在没有它的情况下构建 Angular 项目。

我很确定还有更多方法,但通常在控制器之间传递数据的最佳做法是使用服务。

附带说明,如果您有一个数据对多个控制器通用,最简单的方法是将数据放在服务上并监视该服务的返回值,例如,说我有 isLoggedIn,它可以随时更改,并且很多控制器都希望收到有关它的通知,使用 UserService 并注意它的值:

UserService.isLoggedIn = function() {
    return _isLoggedIn;
}

在你的控制器中:

$scope.$watch(function() {
    return UserService.isLoggedIn();
}, doSomeAction);

我希望这会有所帮助!

【讨论】:

    【解决方案2】:

    这个http://www.jvandemo.com/how-to-resolve-angularjs-resources-with-ui-router/ 似乎是一个不错的指南,基本上,您将解析添加到状态:

    .state("customers", {
            url : "/customers",
            templateUrl: 'customers.html',
            resolve: {
                //any value you want, this function should return a promise, 
                //only when that promise is resolved, it will instantiate the controller
                //Make sure however you add some signal that something is happening because
                //while fetching it can seem like the page is not responding
                customers: ['$http', 'anyOtherServiceYouMightNeed', function($http, otherService){
                    //return a promise
                    return $http.get('api/customers');
                }],
                //and for constant
                constants: ['ConfigService', function(config) {
                     return config.appConstants;
                }]
            },
            //customersCtrl will have customers resolved already
            controller : 'customersCtrl'
          });
    
          app.controller('customersCtrl', ['$scope', 'customers', 'constants', 
                function($scope, customers, consts) {
                //customers will be ready and resolved when the controller is instantiated
                //you can do this with anything you might need inside a controller
          }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-08
      • 2013-11-30
      • 1970-01-01
      • 2021-03-20
      • 2017-02-20
      • 1970-01-01
      • 2015-01-04
      相关资源
      最近更新 更多