我想使用angularjs在我的网站中实现观看次数功能。

该功能与stackoverflow问题视图计数器相同:一直存在。

我当时想拦截HTTP请求,异步更新后端,并在本地更新数据(cookie或localStorage)。

有什么办法吗?

提前致谢

最佳答案

无论使用哪种路由系统,都可以挂接到路由更改事件,然后使用路由名称将请求发送到服务器,以便它可以更新计数器。这是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);
    });
  });
})


您可以合并get / add请求,以便每次触发它时,您都获得页面浏览量,并且在一个请求中增加总计数(如果更适合您)。

对于本演示而言,PageViews服务将保存到localStorage而不是服务器,就像您希望用于实际应用程序那样。 http://jsbin.com/fehoxifabo/1/

07-24 09:50
查看更多