gpt4 book ai didi

javascript - $cacheFactory $resource 页面状态 AngularJS

转载 作者:行者123 更新时间:2023-11-30 06:32:18 25 4
gpt4 key购买 nike

在 View 之间切换以及在 Controller 之间共享的服务上缓存请求时如何保持页面状态?

我有两种看法:

$routeProvider.when('/', {templateUrl: 'views/art.html'});
$routeProvider.when('/bio', {templateUrl: 'views/bio.html'});

art.html 有 Controller 过滤器

.controller('Filters', ['$scope','Imgur', function($scope, Imgur) {
$scope.$on('updateAlbumsList', function(e) {
$scope.albumsList = Imgur.returnAlbumsList();
});
$scope.filterAlbum = function(id) {
Imgur.filterAlbum(id);
};
$scope.init = function() {
Imgur.getAlbumsList(function(){
//A hack to preserve page state
Imgur.loadFilters();
});
};
$scope.init();
}])

Here is a plunker with full source.

现在显然我可以对服务对象做一些事情,比如应用过滤器,它可以更改现有属性、添加新属性,甚至可以根据请求添加新对象。

但是当我切换到 bio.html 并返回到 art.html 时会发生什么?请求再次发出并重新呈现整个页面!我理解这是因为该对象正在被 init() 重新实例化。

  • 如何在 View 之间切换时保持页面状态?

  • 如何将缓存的请求用于其他 Controller 共享的相同服务调用?

最佳答案

据我所知(大约一周前我才开始使用 Angular),Imgur 服务通常被认为是存储状态的好地方。

在我的例子中,我有一个类似的情况,我有一个在多个 View 中使用的搜索指令,但我想在 View 更改之间保持其状态。因此,该指令使用一个服务来保持其自身状态:上次执行的查询、服务器返回的最后一个结果列表等。当指令的 link 函数被调用时,它会使用这些值初始化作用域。

看起来像这样:

// service
myApp.service('SearchService', function(...) {
var previousQuery = null;
var previousResults = [];

this.getPreviousQuery = function() { return previousQuery; };
this.getPreviousResults = function() { return previousResults; };

this.performSearch = function(query) {
previousQuery = query;
...
};
});

// directive (but could just as well have been a controller)
myApp.directive('mySearchForm', function(..., SearchService) {
return {
...
link : function($scope, $element, $attrs) {
$scope.query = SearchService.getPreviousQuery();
$scope.searchResults = SearchService.getPreviousResults();
...
}
};
});

但正如我所说,我是 Angular 初学者,所以不知道这是否是最佳实践。此外,还有其他一些更难存储和检索的“状态”(例如在我的情况下将位置滚动到搜索结果列表中)并且我无法令人满意地解决(仅通过一些 hackery)。

因为我认为服务是单例类,因此实例化一次,它们似乎是存储状态的好地方。如果你没有存储状态的服务(或者这样做感觉很奇怪),$cacheFactory (就像你提到的)也是一个选项。这是一个 jsfiddle这帮助我了解了如何存储和检索它。

关于javascript - $cacheFactory $resource 页面状态 AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16795411/

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