javascript - 服务中的 Angular 存储变量

标签 javascript angularjs

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

To share data across controllers, we need to add a method to our service that stores the username. Remember, the service is a singleton service that lives for the lifetime of the app, so we can store the username safely inside of it.

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;
        }
    };
});

Now, we have a setUsername method in our service that enables us to set the username for the current GitHub user.

我想知道,这样当您打开一个新标签时,用户名不会保留。为应用程序保持这种状态,使用localstorage/cookies不是更好吗?

这是一般的好做法吗?

最佳答案

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

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

您的服务:

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 中的数据都会被刷新。

关于javascript - 服务中的 Angular 存储变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29013529/

相关文章:

javascript - 从所有元素中移除 HTML 5 验证

javascript - 通过单击 Google map 标记来切换 ngShow 属性

javascript - AngularJS 中循环 2 个不同的对象

javascript - ng-click 没有触发与之关联的功能吗?

javascript - 如何在js中将html内容添加到静态文本中

jquery - 在 Kendo UI 网格中仅显示两条记录

javascript - 如何将 promise 链接在一起

javascript - 从字符串中提取主机名

javascript - 是否可以使用 Gatsby 进行推送通知?

angularjs - UI Bootstrap Popover : change width