Kum*_*hav 13 javascript angularjs
如何通过响应GET请求来初始化我的angularjs应用程序.
例如 :-
angular.module('A',[]);
angular.module('A').run( function ($rootScope,$http){
$rootScope.safeApply = function (fn) {
$http.get('url').success(function(result){
// This doesn't work. I am not able to inject 'theConstant' elsewhere in my application
angular.module('A').constant('theConstant', result);
});
var phase = $rootScope.$$phase;
if (phase === '$apply' || phase === '$digest') {
if (fn && (typeof (fn) === 'function')) {
fn();
}
} else {
this.$apply(fn);
}
};
});
Run Code Online (Sandbox Code Playgroud)
我希望在我的应用程序初始化时设置常量,并能够在我的组件之间共享常量.
实现这一目标的最佳方法是什么?
Ben*_*out 10
正如本博文中所述,您可以在引导应用程序之前初始化一个常量:
(function() {
var app = angular.module("A", []);
var initInjector = angular.injector(["ng"]);
var $http = initInjector.get("$http");
return $http.get("/path/to/data.json")
.then(function(response) {
app.constant("myData", response.data);
})
.then(function bootstrapApplication() {
angular.element(document).ready(function() {
angular.bootstrap(document, ["A"]);
});
});
}());
Run Code Online (Sandbox Code Playgroud)
$http.get
应用程序初始化时,结果无法使用.它仅在服务器提供时可用.因此,简单地将该值保持在模块中是不可能的.你冒的风险
但是,您可以执行的操作是将调用包装到$http.get
服务中,并将该服务注入到您希望常量的任何位置.(请注意,无法在配置块中注入服务.)
// grab the "constant"
angular.module('A').factory('almostConstant', function () {
return $http.get('url').then(function(response) {
return response.data;
});
});
// use the "constant"
angular.module('A').controller('controller', function($scope, almostConstant) {
almostConstant.then(function(data){
$scope.almostConstant = data;
});
});
Run Code Online (Sandbox Code Playgroud)
访问almostConstant值的稍微尴尬的模式是由于它的异步性质.它只是在一个未指定的时间可用,因此尝试以同步方式访问它可能会引入许多微妙的时序错误.
一种非常非角色的方法是直接在JS文件中编写常量.目前,您的服务器可以'url'
使用值来回复请求.相反,您可以'url.js'
使用以下字符串来回复请求:
angular.module('A').constant('theConstant', result);
Run Code Online (Sandbox Code Playgroud)
结果显然是你的常数.例如,如果你在后端使用php,它可能看起来像这样:
<?php
header('Content-Type: application/javascript');
$constant = retrieveMyConstant();
?>
angular.module('A').constant('theConstant', <?php echo $constant; ?>);
Run Code Online (Sandbox Code Playgroud)
确保常量看起来像JavaScript值.如果它是一个字符串,'
请将其包装,如果它是一个JSON对象,则写入其序列化等.
在此之后,您只需url.js
在index.html
文件中包含指向的脚本标记.
请注意,此解决方案是同步的,因此如果在服务器上检索常量需要一段时间,则会影响页面加载时间.
归档时间: |
|
查看次数: |
15885 次 |
最近记录: |