AngularJS常数 [英] AngularJS constants

查看:215
本文介绍了AngularJS常数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能注入恒成另一种常量AngularJS?

Is it possible to inject a constant into another constant with AngularJS?

例如。

var app = angular.module('myApp');

app.constant('foo', { message: "Hello" } );

app.constant('bar', ['foo', function(foo) { 
    return { 
        message: foo.message + ' World!' 
    } 
}]);

我需要使用的角度不变的,因为我需要注入一个配置例行程序这一点。即。

I need the use of an angular constant because I need to inject this into a config routine. i.e.

app.config(['bar', function(bar) {
    console.log(bar.message);
}]);

我知道,你只能注入常量和供应商进入配置程序,而我的理解是,你可以做的依赖注入到供应商,但是,它似乎并不为这种情况的最好方法...

I know that you can only inject constants and providers into config routines, and my understanding is that you can do dependency injection into providers, however, it does not seem to be the best method for this sort of scenario...

在此先感谢您的帮助!

推荐答案

您是正确的,这是不可能注册这两个foo和bar为常数。

You are correct, it's impossible to register both foo and bar as constants.

此外,使用供应商作为一种解决方法,你几乎得到了它的权利,只是你必须存储在提供程序实例数据:

Also for using a provider as a workaround, you almost got it right except that you have to store data in a provider instance:

var app = angular.module('myApp', []);

app.constant('foo', {
    message: 'Hello'
});

app.provider('bar', ['foo', function(foo) {
  this.data = {
    message: foo.message + ' World!'
  };

  this.$get = function() {
    return this.data;
  };
}]);

,然后在配置块中,注入一个酒吧的提供程序实例(而不是一个酒吧的实例,因为它是尚未提供在配置阶段):

and then in config block, inject a bar's provider instance (not a bar instance as it isn't available yet in the config phase):

app.config(['barProvider', function(barProvider) {
  console.log(barProvider.data.message);
}]);

希望这有助于。

这篇关于AngularJS常数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆