AngularJS 有没有办法用其他常量定义常量? [英] Is there a way in AngularJS to define constants with other constants?

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

问题描述

我正在尝试用其他常量定义常量,但似乎无法完成,因为当所需的常量依赖时,初始常量尚未准备好.我想确定这是否根本不可能.

I'm trying to define constants with other constants, but it seems that it can't be done, because the initial constant isn't ready when the required constant depending require it. I want to be sure if this isn't possible at all.

目前我有这样的常量:

angular.module('mainApp.config', [])
    .constant('RESOURCE_USERS_DOMAIN', 'http://127.0.0.1:8008')
    .constant('RESOURCE_USERS_API', 'http://127.0.0.1:8008/users')
    // Specific routes for API
    .constant('API_BASIC_INFORMATION', RESOURCE_USERS_API + '/api/info')
    .constant('API_SOCIAL_NETWORKS', RESOURCE_USERS_API + '/api/social')
    ;

后两个常量是我想要完成的.

The second two constants are what I want to accomplish.

推荐答案

AngularJS 定义控制器、服务和其他之间依赖关系的方法是依赖注入 (DI).因此,如果您有一个依赖于服务 B 的控制器 A,则您必须像这样创建它:

The AngularJS way to define dependencies between Controllers, Services and others is by dependency injection (DI). So if you have a controller A that depends on a service B you would have to create it like this:

var myApp = angular.module("exampleApp",[]);

myApp.controller("aCtrl", function(serviceB){
    // Controller functionally here
});

看,AngularJS 将检查 serviceB 依赖项并查找您使用该名称创建的服务.如果你不创建一个,你会得到一个错误.

See, AngularJS will check the serviceB dependency and look for the service you created with that name. If you don't create one you will get an error.

所以,如果你想创建一个依赖于常量 B 的常量 A,你需要告诉 angular A 依赖于 B.但是一个常量不能有依赖.常量可以返回一个函数,但 DI 对常量不起作用.检查此Fiddle,以便您了解DI适用于哪些方法.

So, if you want to create a constant A that depends on constant B, you would need to tell angular that A depends on B. But a constant can't have a dependency. A constant can return a function, but the DI won't work for the constant. Check this Fiddle so you can see for which methods DI work for.

所以回答你的问题,你不能用其他常量定义一个常量.

但你可以这样做:

angular.module('projectApp', [])
  .constant('domain', 'http://somedomain.com')
  .constant('api', '/some/api/info')
  .service('urls', function(domain, api) {this.apiUrl = domain + api;})

  .controller('mainCtrl',function($scope,urls) {

      $scope.url = urls.apiUrl;

  });

检查这个 fiddle 看看它是否有效:

Check this fiddle to see it working:

如果您想了解有关 DI 的更多信息,请查看此帖子.

If you want to understand more about DI, check out this post.

这篇关于AngularJS 有没有办法用其他常量定义常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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