2016-08-25 2 views
0

AngularJS와의 연결에 어려움을 겪고 있으며 여기에 연결된 사용자 정보에 액세스 할 수 있습니다. 내 목표는 연결된 사용자의 정보를 서비스에 저장하여 앱 전체에서 사용할 수 있도록하는 것입니다. 그래서는 나는 그것을 할 방법 :AngularJS : 컨트롤러에서 연결된 사용자 정보에 액세스하십시오.

로그인 기능은 로그인 서비스를 통해 노출, 그 코드는 다음입니다 : 당신이 코드에서 관찰 할 수있는 바와 같이

(function(){ 
var $loginService = angular.module("RockMyTask.LoginService", [ 
    "satellizer", 
    "RockMyTask.ApiService" 
]); 

/** 
* Login service 
* 
* function login(identifier, password, after) 
* Logs the given user. Global data about the user are registered in the root scope. 
* @param identifier The user's identifier (either email or password) 
* @param password The user's password 
* @param success (optional) A callback to execute when the user is successfully logged in. This callback is passed 
* the response object. 
* @param failure (optional) A callback to execute when the log in fails. This callback is passed the response 
* object. 
* 
* function restore() 
* If the user was already logged in, restore the user data in the rootScope. 
* 
* function connectedUser() 
* Return the data of the currently connected user. If the user is not connected an empty object is returned. 
* If the user data hasn't be fetched yet, then an empty object is returned and this object will be filled with 
* the user data as soon as it is received. 
*/ 
$loginService.factory("Login", ["$auth", "$rootScope", "User", 
    function($auth, $rootScope, User) { 
    var obj = {}; 
    var connectedUser = {}; 

    obj.logout = function() { 
     $auth.logout(); 
     //Authorization.clear(); 
     connectedUser = null; 
    }; 

    obj.login = function(identifier, password, success, failure) { 
     var credentials = { 
      user_identifier: identifier, 
      password: password 
     }; 

     $auth.login(credentials).then(function(auth_response) { 
      // fetch user data (with both spectator and rockstar flags set to true) 
      User.me(true, true).then(function(response) { 
       connectedUser = response.data; 
       //TODO add check for DEBUG_MODE 
       console.log("Received connected user data and stored it in connectedUser var"); 
      }, function() { 
       connectedUser = {}; 
      }); 

      // execute provided success callback 
      if (_.isFunction(success)) { 
       success(auth_response); 
      } 
     }, function(response) { 
      connectedUser = null; 

      // execute provided failure callback 
      if (_.isFunction(failure)) { 
       failure(response); 
      } 
     }); 
    }; 

    obj.restore = function() { 
     if ($auth.isAuthenticated()) { 
      User.me(true, true).then(function(response) { 
       connectedUser = response.data; 
      }, function() { 
       connectedUser = null; 
      }); 
     } else { 
      connectedUser = null; 
     } 
    }; 

    obj.getConnectedUser = function(){ 
     if($auth.isAuthenticated && !connectedUser){ 
      User.me(true, true).then(function(response) { 
       connectedUser = response.data; 
      }, function() { 
       connectedUser = null; 
      }); 
     } 
     return connectedUser; 
    }; 

    obj.updateUserInfo = function(user){ 
     connectedUser = user; 
    }; 

    obj.isConnectedUserRockstar = function(){ 
     return connectedUser.rocker != null; 
    }; 
    obj.isConnectedUserSpectator = function(){ 
     return connectedUser.spectator != null; 
    }; 

    return obj; 
}]); 
})(); 

가 성공적으로 로그인시, I 출시 HTTP 요청 (User.me(true, ture))은 반환 된 데이터 (연결된 사용자에 대한 정보를 나타내는)를 서비스의 임시 변수 connectedUser에 저장합니다.

obj.getConnectedUser = function(){ 
     if($auth.isAuthenticated && !connectedUser){ 
      User.me(true, true).then(function(response) { 
       connectedUser = response.data; 
      }, function() { 
       connectedUser = null; 
      }); 
     } 
     return connectedUser; 
    }; 

이 기능 검사를 사용자 인 경우 :

누구의 코드 여기에보고됩니다 getConnectedUser라는 로그인 서비스에, 내가 구현 한 응용 프로그램의 어떤 지점에서 함수를 연결된 사용자 정보에 액세스하려면 참으로 인증되고 변수 connectedUser가 이미 정확하게 채워져 있고 그렇지 않으면 다시 HTTP 함수가 데이터를 검색하도록 트리거합니다 (그렇지 않으면 간단히 connectedUser var를 반환 함).

이제 내 문제는 다음과 같습니다. 로그인 성공 후 사용자를 리디렉션하는 페이지는 로그인 서비스를 통과 한 컨트롤러를 사용합니다. 컨트롤러는 연결된 사용자 정보를 검색하려고하지만 결과는 null 포인터입니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까??

컨트롤러의 코드는 (단지의 경우에도 아주 간단한 경우에) :

$scope.user = Login.getConnectedUser(); 

EDIT 1

내가 HTTP 요청이 성공과 반환 된 데이터를 가지고 있음을 볼 수있는 브라우저에서 콘솔을 보면 입니다 : 내가 컨트롤러에 $scope.user의 변수에 액세스하려고 할 때

이전에 언급 한 바와 같이
{"id":3,"email":"[email protected]","name":"Michele","surname":"Imperiali","locale":"it_IT","picture":"https:\/\/storage.rockmytask.it\/users\/profile_image\/3.jpeg","birthday":"1982-06-23","gender":"M","country":"IT","province":"Lombardia","city":"Milano","zip":"20100","street":"190 Grover Expressway","mobile_phone":"(437)924-8282","home_phone":"239-250-3166x783","username":"spectator","validated":true,"timezone":"Europe\/Rome","created_at":"2016-04-01T12:50:53+0000","rocker":null,"spectator":{"description":"I need help with my garden !"}} 

, 내가 널 포인터 예외를 얻을.

+0

consol.logging으로'User.me (true, ture)'에 정확한 데이터를 가지고 있는지 확인할 수 있습니까? –

+0

@JahongirRahmonov 예 가능합니다. 질문에 자세한 내용을 추가했습니다 – miks87

+0

전체 로그인 서비스 코드를 게시 할 수 있습니까? –

답변

-1

난 당신이 connectedUser null로 설정하는 이유가 거기에 문제가

, function() { 
      connectedUser = null; 
     } 

과 관련이있다 생각하십니까? 당신은 나쁜 응답을받을 경우

이 만 설정합니다 connectUser
obj.getConnectedUser = function(){ 
    if($auth.isAuthenticated && !connectedUser){ 
     User.me(true, true).then(function(response) { 
      connectedUser = response.data; 
     }, function(error) { 
      connectedUser = null; 
     }); 
    } 
    return connectedUser; 
}; 

null로로서 : 당신은 당신이 다음 일을 백엔드 또는 나쁜 반환에서 오류가 발생하는 경우 null로 설정할 때문에 이유 인 경우 이제 connectedUsers가 null로 설정되고 널 포인터를 설명하는 것처럼 보입니다.

+0

Jeffrey에게 감사 드리지 만, 귀하의 솔루션이 좋다고 생각하지 않습니다. 'then' 함수의 표기법은 성공과 실패에 대한 두 가지 함수를 정의하는 것입니다. 두 번째 매개 변수 인 내 함수는 HTTP 요청이 실패한 경우에만 트리거됩니다. 사실, 내가 connectedUsers = null을 body라고 말하면, 문제는 여전히 동일합니다 ... – miks87

+1

미안하지만, 나는 아직 충분한 명성을 얻지 못했습니다. 내 다른 생각은 함수 내에서 약속을 기다리지 않고 실제로 약속을 반환해야한다는 것입니다. 그래서 당신은 함수가 http 요청을 반환하게 할 것이다. 컨트롤러에서 Login.getConnectedUser()를 누른 다음 (function (response) {$ scope.user = response.data}); –

+0

안녕하세요 제프리, 네 말이 맞습니다. 나는 서비스에서 그때를 수행하고 거기에 연결된 사용자 정보를 저장하고 응용 프로그램의 다른 부분에서 후속 요청에 사용할 수있게하기 때문에 내가 말한대로하지 않습니다. 그러나 귀하의 의견은 올바른 방향으로 나를 지적했다. 저는 곧 내 솔루션을 게시 할 것입니다. 건배! – miks87

관련 문제