Reputation: 3084
I want to implement the number of views feature in my website with angularjs.
The feature is the same as stackoverflow question view counter : it's persisted.
I was thinking of intercepting the http request, updating the backend asynchronously and update the data locally ( cookie or localStorage).
Is there any way to do it?
Thanks in advance
Upvotes: 1
Views: 4955
Reputation: 43755
With whatever routing system you're using, you could just hook onto the route change event and send a request to the server with the route name so that it can update the counter. Here's an example with ui-router.
.run(function($rootScope, PageViews) {
$rootScope.$on('$stateChangeStart', function(e, toState) {
// add a view
PageViews.add(toState.name);
// request the total views for this state from the server
PageViews.get(toState.name).then(function(resp) {
// add 1 to the result if you want to count the current view
$rootScope.pageViews = resp.data + 1;
// let the server know another user has viewed this state
PageViews.add(toState.name);
});
});
})
You could combine the get/add request so that every time you trigger it, you get the page views and also increment the total count in one request if that works better for you.
For the sake of this demo, the PageViews
service is saving to localStorage instead of a server like you would want to use for a real application. http://jsbin.com/fehoxifabo/1/
Upvotes: 2
Reputation: 1317
I think you should just have the backend print the pageview number on the response, and that number should be increasing everytime by updating your database. If you insist on using an async API call to do it, here's a workaround:
You can intercept every anchor click and make an async call before letting the link take you wherever (a jQuery example):
$(window).click(function(event){
if(event.target.is('a[href]')){
yourAsyncFunction();
window.location.href = $(event.target).attr('href'); // Use this if you want to
// actually go where the anchor
// takes you
}
return false;
});
Upvotes: 0