服务中的角度存储变量

时间:2015-03-12 15:15:02

标签: javascript angularjs

我目前正在阅读ng-book,只是想知道这个与服务相关的代码示例是否是一个好习惯:

  

要跨控制器共享数据,我们需要为我们添加一个方法   存储用户名的服务。请记住,服务是一个   在应用程序的生命周期中存在的单身人士服务,所以我们可以   将用户名安全地存储在其中。

angular.module('myApp.services', [])
    .factory('githubService', function($http) {
        var githubUrl = 'https://api.github.com',
            githubUsername;
        var runUserRequest = function(path) {
        // Return the promise from the $http service
        // that calls the Github API using JSONP
        return $http({
            method: 'JSONP',
            url: githubUrl + '/users/' +
            githubUsername + '/' +
            path + '?callback=JSON_CALLBACK'
        });
    }
    // Return the service object with two methods
    // events
    // and setUsername
    return {
        events: function() {
            return runUserRequest('events');
        },
        setUsername: function(username) {
            githubUsername = username;
        }
    };
});
  

现在,我们的服务中有一个setUsername方法,可以让我们使用   设置当前GitHub用户的用户名。

我想知道,这样打开新标签时用户名就不会持续存在。使用localstorage / cookies来保持应用程序的这种状态不是更好吗?

这是一般的好习惯吗?

2 个答案:

答案 0 :(得分:1)

你可以做到这两点。在私有变量中将此类数据保存在服务中可以隔离它,您可以控制读/写以进行某种验证。这样您就不允许在服务内部的任何地方修改数据。

您可以做的是在服务中添加一个保存功能,在存储中保存所需的数据,以及在app.run方法上调用的公共调用功能。

您的服务:

angular.module('myApp.services', [])
  .factory('githubService', function($http) {
    var githubUrl = 'https://api.github.com',
      githubUsername;
    var runUserRequest = function(path) {
      // Return the promise from the $http service
      // that calls the Github API using JSONP
      return $http({
        method: 'JSONP',
        url: githubUrl + '/users/' +
          githubUsername + '/' +
          path + '?callback=JSON_CALLBACK'
      });
    }
    //Saves the data inside localStorage
    var save = function() {
      localStorage.setItem('githubData', guthubUserName);
    }

    // Return the service object with two methods
    // events
    // and setUsername
    return {
      events: function() {
        return runUserRequest('events');
      },
      setUsername: function(username) {
        githubUsername = username;
        save(); // keeps the username always up to date
      },
      recall : function(){
        githubUsername = localStorage.getItem('githubData');
      }  
    };
  });

你的main.js:     var app = app.module(' yourGitHubApp',[' myApp.services'])

app.run(function(githubService){
 githubService.recall();
})

因此,每次重新加载应用程序时,都会刷新localStorage中的数据。

答案 1 :(得分:0)

  

我想知道,这样打开新标签页时用户名就不会保留。

因为如果您在新标签页中打开某个应用,则会再次重新初始化整个应用代码库,包括githubService,因此githubUsername会再次失效。

如果您需要状态在应用程序重新加载时保持不变,那么您应该使用某种存储,例如localStorage。

相关问题