gpt4 book ai didi

javascript - 确保 Angular Controller 中的函数只运行一次

转载 作者:行者123 更新时间:2023-11-30 16:28:50 26 4
gpt4 key购买 nike

我有一个从我的服务调用函数的 Controller ,我只想从网络加载一次数据,并大概缓存它(在 rootScope 中?但这可以等待...)。

我尝试将函数调用包装在 init() 中,但它似乎没有帮助...我每次加载部分时都会看到函数被调用。

也许我的路由有些天真?

这是一些代码:

app.js

'use strict';

var tab = angular.module('tab', ['ngRoute', 'tab.controllers', 'tab.services']);

tab.config(['$routeProvider', function($routeProvider) {
$routeProvider.

// a bunch of other logic here

when('/curate', {
templateUrl: '_partials/curate.html',
controller: 'CurateController'
}).

otherwise({
redirectTo: '/splash'
});
}]);

controllers.js

// other controllers etc 

.controller('CurateController', function($scope, $routeParams, ParseService) {

// Here's where I'm trying to call the function once.
// Obviously, if I don't have this in the init() it also calls every time I route to it
$scope.init = function () {
ParseService.getArticles(function(results) {
console.log("Articles: " + results);
// do stuff with data here
});
};

})

services.js

angular.module('tab.services', []);

angular.module('tab.services')

/* PARSE */

.factory('ParseService', function() {

// Vars etc

var ParseService = {
name: "Parse",


// The function in question
getArticles : function getArticles(callback) {
var query = new Parse.Query(Article);
query.find({
success : function(results) {
callback(results);
},
error : function(error) {
alert("Error" + error.message);
}
});
},

};


return ParseService;
});

curate.html

<section>
<div class="container-fluid" ng-controller="CurateController" ng-init="init()">

<!-- STUFF -->


</div>
</section>

最佳答案

您没有展示您的服务。只需将其缓存在服务 $http 调用

中即可
$http.get(url, { cache: true}).success(...);

--- 更新

您应该从您的服务中返回 promise ,而不是将回调传递给它。

查看 Parse 文档,我无法找到一种自动为您缓存 web 数据的方法。

您可以实现自己的缓存机制,我建议在服务中,而不是在 Controller 中。

-- 编辑 2

请记住,服务是单例的。因此,根据设计,它只会被构建一次。

关于javascript - 确保 Angular Controller 中的函数只运行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33665434/

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