Facebook 사용자 인증을 처리하는 맞춤 AngularJS 팩토리를 만들고 있습니다.비동기 공장 호출 (FB API) 후 컨트롤러 값이 업데이트되지 않습니다.
내 컨트롤러에서 FBUser
개체에 바인딩되지만 내보기가 {{user.name}}
에 대해 아무것도 출력하지 않습니다. 그러나 컨트롤러 블록을 1 초에 랩핑하면 $timeout
이 작동합니다. 난 $rootScope.$apply()
내 FBUser 값을 업데이 트 내보기를 일으킬 것이라고 생각했지만 그렇지 않습니다. 이상적으로 나는 가능한 한 컨트롤러 내에서 작은 작업을하고 싶습니다. 왜냐하면 나중에 내 앱의 다른 모델 컨트롤러가 공장에서 사용자 객체를 사용하기를 원하기 때문입니다.
angular.module('tatsdb.fbauth', ['tatsdb.api'])
.factory('FBAuth', ['$rootScope', function($rootScope) {
var FBUser = {};
var FBAuth = {};
FBAuth.authResponseChange = function() {
FB.Event.subscribe('auth.authResponseChange', function(response) {
if (response.status === 'connected') {
FBAuth.getUserAsync();
}
else {
console.log('not connected');
}
});
};
FBAuth.getUserAsync = function() {
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
$rootScope.$apply(function() {
FBUser = response;
});
});
};
FBAuth.getUser = function() {
return FBUser;
};
FBAuth.logout = function() {
FB.logout(function(response) {
FBUser = {};
});
};
return FBAuth;
}])
.run(['$window', 'FBAuth',
function($window, FBAuth) {
$window.fbAsyncInit = function() {
FB.init({
appId : '278156419011935',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FBAuth.authResponseChange();
};
// Load the SDK asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
}])
.controller('FBUserController', ['$scope', 'FBAuth', function($scope, FBAuth) {
$scope.user = FBAuth.getUser();
}]);
범위 내에서 공장에서 선언 된 변수 인 FBUser를 어떻게해야합니까? 내보기에 {{FBUser.name}}을 (를) 씁니까? 이 질문의 주된 원인 인 응답을 받기 전에 컨트롤러가 실행 중임을 이해합니다. FBUser.name이 채워지면 어떻게 뷰를 업데이트 할 수 있습니까? – Fenda
@Fenda 나 자신이 서비스를 사용할 것이다. 이 서비스는 API에서 얻은 응답을 할당받는 FBUser 멤버를 보유합니다. 그런 다음 내 컨트롤러에서'$ scope.FBUser = facebookApiService.FBUser; '를 수행하고 뷰에서는'{{FBUser.name}}'을 수행 할 것입니다. 나는 아직 공장에서 일한 적이 없지만 서비스를 사용하는 것이 훨씬 쉽고 직관적이라고 생각한다. –
기본적으로 내가 이미하고있는 것이 아닌가요? FBUser에 API의 응답이 할당되고 컨트롤러에서 바인딩에 바인딩되었습니다. 서비스 나 팩토리를 사용하여 볼 수있는 한 여기에서는 동일합니다. – Fenda