我使用以下函数从REST API获取用户,按偏移量分页。 On Success-Callback
,使用新的偏移量递归调用该函数以获取下一个用户垃圾。
问题:如果我切换或离开视图,FetchAttendee-Function
会一直运行,直到获取所有用户为止。但是为了提高性能,我想停止为用户提取。
fetchAttendees(event_id, offset);
function fetchAttendees(event_id, offset) {
AttendeeFactory(offset).show({id: event_id},
function success(response) {
[ DO SOMETHING WITH RESPONSE ]
fetchAttendees(event_id, offset);
},
function (error) {
});
}
那么,是否可以停止在视图中调用 fetchAttendee-Function 离开事件?
$scope.$on("$ionicView.leave", function(scopes, states) {
[ ...]
});
AttendeeFactory
.factory('AttendeeFactory', function ($resource) {
return function (offset) {
return $resource('http://10.0.0.6:8000/backend/attendees/:id/', {}, {
show: { method: 'GET', headers: {'attendee-offset': offset}, isArray: true }
});
};
})
答案 0 :(得分:2)
这是伪代码(未经测试,你想做什么)
// in your controller
app.controller('YourController', ['$scope', 'AttendeeFactory', function($scope, AttendeeFactory) {
...
AttendeeFactory.fetchAttendees(event_id, offset);
...
}]);
// in the state change handler that matches leaving your view
AttendeeFactory.pause();
// in your service/factory
app.factory('AttendeeFactory', function($resource) {
var isPaused = true;
function fetchAttendees(event_id, offset) {
isPaused = false;
fetchAttendeesRecursive(event_id, offset);
}
function fetchAttendeesRecursive(event_id, offset) {
if (!isPaused) {
Attendee(offset).show(
{id: event_id},
function success(response) {
[ DO SOMETHING WITH RESPONSE ]
fetchAttendees(event_id, offset);
},
function (error) {}
);
}
}
function Attendee(offset) {
return = $resource(
'http://10.0.0.6:8000/backend/attendees/:id/',
{},
{
show: {
method: 'GET',
headers: {'attendee-offset': offset},
isArray: true
}
}
);
}
function pause() { isPaused = true; }
return {
fetchAttendees: fetchAttendees,
pause: pause
};
});
如果[DO SOMETHING WITH RESPONSE]包括将其绑定到视图的范围,则必须添加代码以使服务通知控制器数据已更改。
在这种情况下,您可以使用$ rootScope,$ on和$ emit在提取与会者时从服务发出消息,以便控制器可以监听并更新。这是一个简单的例子:
// in the controller
$rootScope.$on("AttendeeFetchedEvent", function($event, data){
// do something with data
});
// in the factory/service
$scope.$emit("AttendeeFetchedEvent", dataToSendToController);