簡體   English   中英

在角度js中解析函數內部的值

[英]resolving values inside of a function in angular js

我在名為Auth.js的文件中包含此代碼。 hasRole:function(){console.log(currentUser); 返回currentUser.role; // role是一個對象數組,但是給出了undefined}

登錄后,在重定向到任何地方之前,我需要解析hasRole的值。

登錄看起來像這樣:

 var role=[];

login: function(user, callback) {
        var cb = callback || angular.noop;
        var deferred = $q.defer();

        $http.post('/auth/local', {
          email: user.email,
          password: user.password
        }).
        success(function(data) {
          $cookieStore.put('token', data.token);
          currentUser = User.get();
          console.log(currentUser);//gives an unresolved promise (output is given after this piece of code.

           role = currentUser.role;  //gives undefined 
          deferred.resolve(data);    
          return cb();
        }).
        error(function(err) {
          this.logout();
          deferred.reject(err);
          return cb(err);
        }.bind(this));

        return deferred.promise;
      }}

並被稱為如下:

 $scope.login = function(form) {
      $scope.submitted = true;

      if(form.$valid) {
        Auth.login({
          email: $scope.user.email,
          password: $scope.user.password
        })
        .then( function() {
          // Logged in, redirect to home
         var role = Auth.hasRole();
         console.log(role) //gives undefined.
        //Need to redirect on basis of value of role
        /*if(role.priority >= 1){
          $location.path('/admincontrol');

        }else{
          $location.path('/');

        }*/


        })
        .catch( function(err) {
          $scope.errors.other = err.message;
        });
      }
    };

如何在此處訪問currentUser.role? 登錄后和重定向之前,我需要在$ scope.login中具有其值,以便可以根據其值進行重定向。

編輯:用戶服務如下所示:

'use strict';

angular.module('createProjectApp')
  .factory('User', function ($resource) {
  //  return $resource('/api/users/:id/:controller', {
    return $resource('/api/customUsers/:id/:controller', {
      id: '@_id'
    },
    {
      changePassword: {
        method: 'PUT',
        params: {
          controller:'password'
        }
      },
      get: {
        method: 'GET',
        params: {
          id:'me'
        }
      }
      });
  });

在登錄時進行控制台操作時, currentUser如下所示: 在此處輸入圖片說明

User.get()本身是一個返回承諾的函數。 您將必須等待諾言完成,然后再繼續操作,如

currentUser.then(function() {
  console.log(currentUser);
  role = currentUser.role;  //gives undefined 
  deferred.resolve(data);    
  return cb();
}

因為您正在使用諾言,所以不需要cb()本身-但您可能有一些特別的想法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM