gpt4 book ai didi

javascript - AngularJS 应用程序 : Load data from JSON once and use it in several controllers

转载 作者:数据小太阳 更新时间:2023-10-29 05:03:52 26 4
gpt4 key购买 nike

我正在开发一个使用 AngularJS 作为框架的移动应用程序,目前我的结构与此类似:

app.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/', {
templateUrl : 'pages/home.html',
controller : 'homeCtrl'
})

.when('/one', {
templateUrl : 'pages/one.html',
controller : 'oneCtrl'
})

.when('/two', {
templateUrl : 'pages/two.html',
controller : 'twoCtrl'
});
}]);

app.controller('homeCtrl', ['$scope', function($scope) {

}]);

app.controller('oneCtrl', ['$scope', function($scope) {

}]);

app.controller('twoCtrl', ['$scope', function($scope) {

}]);

然后我用 ng-view 显示内容:

<div class="ng-view></div>

一切正常,但我需要从 JSON 文件加载数据以填充应用程序的所有内容。我想要的是制作一个 AJAX 调用仅一次,然后通过我所有不同的 Controller 传递数据。在我的第一次尝试中,我想创建一个在其中包含 $http.get() 的服务,并将其包含在每个 Controller 中,但它不起作用,因为它每次都会发出不同的 ajax 请求注入(inject)并使用该服务。由于我是 angular 的新手,我想知道什么是最好的方法或更“Angular 方法”来实现这一目标而不会搞砸。

编辑:我正在添加服务代码,这只是一个简单的$http.get请求:

app.service('Data', ['$http', function($http) {
this.get = function() {
$http.get('data.json')
.success(function(result) {
return result;
})
}
});

最佳答案

初始化 promise 一次,并返回对它的引用:

无需初始化另一个 promise 。 $http 返回一个。

只需添加一个 .then() 调用你的 promise 来修改结果

angular.module('app', [])
.service('service', function($http){
this.promise = null;
function makeRequest() {
return $http.get('http://jsonplaceholder.typicode.com/posts/1')
.then(function(resp){
return resp.data;
});
}
this.getPromise = function(update){
if (update || !this.promise) {
this.promise = makeRequest();
}
return this.promise;
}
})

Codepen example

编辑:您可以考虑改用 $http 缓存。它可以达到相同的结果。 From the docs :

If multiple identical requests are made using the same cache, which is not yet populated, one request will be made to the server and remaining requests will return the same response.

关于javascript - AngularJS 应用程序 : Load data from JSON once and use it in several controllers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30784714/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com