AngularJS常数

编程入门 行业动态 更新时间:2024-10-28 04:27:22
本文介绍了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常数

本文发布于:2023-08-01 08:59:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1267059.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:常数   AngularJS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!