假设有多个链接。每次链接单击均由控制器处理。考虑一下情况:
/search
是用户输入关键字并按下搜索按钮的地方。/search
)在4
点,当用户第一次访问angulajs时会加载页面。如何使Angulajs成为非状态而是进行处理?例如。如果处理未完成,则会显示进度条,但是如果处理完成,则会提供处理结果中的数据并呈现新页面。如何实现?
注释
答案 0 :(得分:0)
您可以使用angularjs服务记住进行api调用并从中获取数据的“过程”。 这是一个简单的实现。
这里的整个想法是创建一个可以进行api调用的角度服务, 存储数据以及数据状态,以便可以从angularjs的其他模块访问它。请注意,由于angularjs服务为单例,这意味着将保留所有状态。
app.controller('searchController',function(searchService){
// in your initialization function call the service method.
var searchState = searchService.getState();
// search state has your loading variables. you can easily check
// and procede with the logic.
searchState.loading // will have loading state
searchState.data // will have data
searchState.error // will have error if occured.
});
//在您的控制器中
{{1}}
即使您从页面导航。角度服务将保留状态,您可以从应用程序中的任何位置获取相同的数据。您只需注入服务并调用getter方法。
答案 1 :(得分:0)
基于这个问题(多一点上下文或代码将有助于使答案更有针对性),当考虑angularJS中的异步操作时,建议始终在服务中使用getter和setter以避免多次REST调用。
请注意-服务是单例,而不是控制器。
例如:
angular.module('app', [])
.controller('ctrlname', ['$scope', 'myService', function($scope, myService){
myService.updateVisitCount();
$scope.valueFromRestCall = myService.myGetterFunctionAssociated(param1, param2);
//Use $scope.valueFromRestCall to your convinience.
}]
.service('myService', ['$http', function($http){
var self = this;
self.numberOfVisits = 0;
self.cachedResponse = null;
self.updateVisitCount = function(){
self.numberOfVisits+=1;
}
self.myGetterFunctionAssociated = function(param1, param2){
if self.cachedResponse === null || self.numberOfVisits === 0 {
return $http.get(url).then(function(response){
self.cachedResponse = response;
return response;
});
}
else {
return self.cachedResponse;
}
}
return {
updateVisitCount: function(){
self.udpateVisitCount();
},
myGetterFunctionAssociated : function(param1, param2){
return self.myGetterFunctionAssociated(param1, param2);
}
}
}]