制作 Angular 服务来维护计数器

Making an Angular Service to Maintain a counter

我正在尝试使用 angular 服务。作为测试,我想制作一个简单的计数器,它在多个控制器和整个浏览器生命周期中递增。我的服务似乎在每个控制器中都重新初始化,有什么想法吗?

注意:控制器位于不同的页面上 - 因此需要重新加载页面

angular.module('myApp').service('Session', function($http) {

    this.inc = function() {
        console.log("INC Called and Global is :" + this.count);
        if(this.count) {
            this.count++;
        } else {
            this.count = 0;
        }

   };

    this.get = function() {
        return this.count;
    };

});

然后在我调用的控制器中

Session.inc();

Session.get();

你的设置没问题,但是你的逻辑有问题:

   this.inc = function() {
        console.log("INC Called and Global is :" + this.count);
        if(this.count) {
            this.count++;
        } else {
            this.count = 0;
        }

   };

第一次是 运行,this.count 将被初始化为 0,这将在下一次评估为 false。将其更改为:

 this.count = 0;
 this.inc = function() {
    this.count++;
 };

更容易理解。

Plnkr:http://plnkr.co/edit/WoPVQZuzQ7Ow781OOgtj?p=preview

编辑:作者似乎试图在页面更改时保持服务状态。为此,您可以使用 localstorage:

 this.count = localStorage.getItem('counter') || 0;
 this.inc = function() {
    this.count++;
    localStorage.setItem('counter', this.count);
 };