How to return a resolved promise from an AngularJS Service using $q?

后端 未结 7 1619
Happy的楠姐
Happy的楠姐 2020-12-05 17:23

My service is:

myApp.service(\'userService\', [
  \'$http\', \'$q\', \'$rootScope\', \'$location\', function($http, $q, $rootScope, $location) {
    var defe         


        
7条回答
  •  -上瘾入骨i
    2020-12-05 17:47

    Here's the correct code for your service:

    myApp.service('userService', [
      '$http', '$q', '$rootScope', '$location', function($http, $q, $rootScope, $location) {
    
        var user = {
          access: false
        };
    
        var me = this;
    
        this.initialized = false;
        this.isAuthenticated = function() {
    
          var deferred = $q.defer();
          user = {
            first_name: 'First',
            last_name: 'Last',
            email: 'email@address.com',
            access: 'institution'
          };
          deferred.resolve(user);
          me.initialized = true;
    
          return deferred.promise;
        };
      }
    ]);
    

    Then you controller should align accordingly:

    myApp.run([
      '$rootScope', 'userService', function($rootScope, userService) {
        return userService.isAuthenticated().then(function(user) {
          if (user) {
            // You have access to the object you passed in the service, not to the response.
            // You should either put response.data on the user or use a different property.
            return $rootScope.$broadcast('login', user.email);  
          } else {
            return userService.logout();
          }
        });
      }
    ]);
    

    Few points to note about the service:

    • Expose in a service only what needs to be exposed. User should be kept internally and be accessed by getters only.

    • When in functions, use 'me' which is the service to avoid edge cases of this with javascript.

    • I guessed what initialized was meant to do, feel free to correct me if I guessed wrong.

提交回复
热议问题