服务:Init函数不会启动数据

时间:2016-12-21 08:40:46

标签: javascript angularjs ionic-framework

我有一个使用Ionic构建的应用程序,我在其中列出文章,在打开一篇文章时,我使用init中的函数UserService启动用户数据:

angular.module('coop.services')
.factory('UserService', function(
  $http,
  AppSettings,
  $rootScope,
  $auth,
  $q,
  $resource,
  $cordovaFileTransfer
) {
  var service = {
    user: {},

    init: function() {
      var user = localStorage.getItem('coop_user');

      if (user) {
        service.user = JSON.parse(user);
      }

      service.engagementResource = $resource(
        AppSettings.apiUrl + '/user/:userId/engagements',
        {
          userId: service.user.id
        }
      );
    },

    set: function(user) {
      service.user = user;
      localStorage.setItem('coop_user', JSON.stringify(user));
    },

    get: function() {
      return service.user;
    },

    getProfilePicture: function(user, size) {
      return user && user.photo
        ? AppSettings.mediaServer + '/imagecache/user' + size + '/users/' + user.photo
        : 'images/pic.jpeg';
    },

    clear: function() {
      service.user = {};
      localStorage.removeItem('coop_user');
    },

    sendContactConfirmation: function(contact, reset) {
      var defer = $q.defer();

      if(reset == 'reset'){
        var endpointUrl = $http.post(AppSettings.apiUrl + "/users/reset", { phone: contact });
      }
      else {
        var endpointUrl = $http.post(AppSettings.apiUrl + "/users", { phone: contact });
      }

      endpointUrl.then(function(result) {
        service.set(result.data.user);
        defer.resolve(result);
      }, function(error) {
        defer.reject(error);
      });

      return defer.promise;
    },

    sendActivation: function(userId, code, form) {
      var defer = $q.defer();

      $http.put(AppSettings.apiUrl + '/users/' + userId + '/activate', { code: code }).then(function(result) {
        if (form == 'register'){
          $auth.setToken(result.data.token);
        }

        defer.resolve(result);
      }, function(error) {
        defer.reject(error);
      });

      return defer.promise;
    },

    resetPassword: function(userId, password) {
      var defer = $q.defer();

      $http.put(AppSettings.apiUrl + '/users/' + userId + '/reset', { password: password }).then(function(result) {
        service.set(result.data.user);

        defer.resolve(result);
      }, function(error) {
        defer.reject(error);
      });

      return defer.promise;
    },

    save: function(user) {
      var defer = $q.defer();

      $http.put(AppSettings.apiUrl + '/users/' + user.id, user).then(function(result) {
        $auth.setToken(result.data.token);
        service.set(result.data.user);

        defer.resolve(result);
      }, function(error) {
        defer.reject(error);
      });

      return defer.promise;
    },

    saveProfilePicture: function(pictureUrl) {
      var defer = $q.defer();

      $cordovaFileTransfer.upload(
        AppSettings.apiUrl + '/users/' + service.user.id + '/pic',
        pictureUrl,
        {
          headers: {
            'Accept': 'application/json',
            'Authorization': 'Bearer ' + $auth.getToken()
          }
        },
        true
      ).then(function(result) {
        var user = JSON.parse(result.response).user;
        service.set(user);

        defer.resolve(user);
      }, function(error) {
        defer.reject(error);
      });

      return defer.promise;
    },

    join: function(engagementId){
      return service.engagementResource.save({
        engagementId: engagementId
      });
    },

    leave: function(engagementId) {
      return service.engagementResource.delete({
        engagementId: engagementId
      });
    },

    getEngagements: function() {
      return service.engagementResource.query();
    },
  };

  service.init();

  return service;
});

但是当我用新用户打开单篇文章页面时,我没有得到用户的任何数据,我在控制台中得到null

init: function() {
      var user = localStorage.getItem('coop_user');
       console.log(user);

然后,我对后端的请求失败,因为我没有发送用户数据。在登录时,我将localStorage中的用户数据设置为auth controller,如下所示:

$scope.loginPromise.then(function(response) {
        UserService.set(response.data.user);

如果我刷新页面,那么我会为用户获取数据,但之前不会。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

在您调用服务上的其他功能之前,从应用程序的运行或控制器启动服务:

UserService.init();