2017-03-06 78 views
1

在我的模块的恒定值,我不断添加像下面无法获得angularjs服务

var app = angular.module("myapp", ["ngRoute"]).constant("myConfig", { 
"url": "http://localhost", 
"port": "80" 
}); 

我正试图获得的恒定值,在我的服务像下面,但我没能得到任何东西。

app.service('MyService', function MyService($http, myConfig) { 

} 

什么是正确的方法来获得服务中的常量值?

+1

'myConfig'是不确定的或者是你得到了一些错误?我做了一个[jsFiddle](https://jsfiddle.net/The_Bear/jg0mmaqr/3/),我没有任何问题注入常量到服务... –

+0

@ The.Bear我没有通过myConfig在控制器。所以你将myConfig传递给控制器​​,然后控制器向前传递。这是唯一的方式还是更好的方法? – Happy

+0

有三种方法可以在服务中注入常量:内联数组注释,'$ inject'属性注释和隐式注释。哪一个更好是一个意见问题。请参阅[AngularJS开发人员指南 - 依赖注入注释](https://docs.angularjs.org/guide/di#dependency-annotation) – georgeawg

回答

0

您可以创建服务函数并通过服务函数返回常量值。或者,您只需将常数注入控制器并直接调用常量值即可。

var app = angular.module("myapp", []); 
 

 
app.constant("myConfig", { 
 
"url": "http://localhost", 
 
"port": "80" 
 
}); 
 

 
app.service('MyService', function MyService($http, myConfig) { 
 
    var vm = this; 
 
    
 
    vm.getConst = function(){ 
 
     return myConfig.url; 
 
    } 
 
}); 
 
app.controller("ctrl",function($scope,MyService,myConfig){ 
 
    //get it throuth servive 
 
\t 
 
    console.log(MyService.getConst()); 
 
    
 
    //get it from controller 
 
    
 
    console.log(myConfig.url); 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="myapp" ng-controller="ctrl"> 
 

 
</div>

+0

由于'getConst'函数省略了'返回'语句,该函数返回[原始值'undefined'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined)。 – georgeawg

+0

@georgeawg什么是你的意思是省略返回。我更新它,'getConst'返回值 –