我在项目中使用 Mozilla Persona。我想在 onlogin
之后更新 loggedInUser
。但是 loggedInUser
是传递给 navigator.id.watch()
的对象的属性。
navigator.id.watch()
被调用一次(在 AngularJS 服务中)。
我应该再次调用它,传递完整的对象吗?好像不太对。我错了吗? =P
这是我的服务:
app.factory('persona', function ($rootScope, $http) {
navigator.id.watch({
loggedInUser: null,
onlogin: function onlogin(assertion) {
console.log(this);
$http.post('/signIn', { assertion: assertion })
.then(function (data, status, headers, config) {
$rootScope.$broadcast('signIn', data.data);
}, function (data, status, headers, config) {
$rootScope.$broadcast('signInError', data.data);
});
},
onlogout: function onlogout(param) {
$http.get('/signOut')
.then(function (data, status, headers, config) {
$rootScope.$broadcast('signOut', data.data);
}, function (data, status, headers, config) {
$rootScope.$broadcast('signOutError', data.data);
});
}
});
return {
signIn: function signIn() {
navigator.id.request();
},
signOut: function signOut() {
navigator.id.logout();
}
};
});
最佳答案
难道你不能让 loggedInUser 变成全局的或者至少在与你的 navigator.id.watch 方法相同范围内的“局部全局”,就像 MDN 示例一样?
之后,您可以从 Persona 服务获取 JSON 响应,其中包含一些数据,包括电子邮件。因此,您可以在 AJAX 响应中传递该数据并填充 loggedInUser 变量
var currentUser = 'bob@example.com';
navigator.id.watch({
loggedInUser: currentUser,
onlogin: function(assertion) {
$.ajax({
type: 'POST',
url: '/auth/login', // This is a URL on your website.
data: {assertion: assertion},
success: function(res, status, xhr) { window.location.reload(); },
error: function(xhr, status, err) {
navigator.id.logout();
alert("Login failure: " + err);
}
});
},
onlogout: function() {
$.ajax({
type: 'POST',
url: '/auth/logout', // This is a URL on your website.
success: function(res, status, xhr) { window.location.reload(); },
error: function(xhr, status, err) { alert("Logout failure: " + err); }
});
}
});
来自 MDN 的 JSON 响应示例:
{
"status": "okay",
"email": "bob@eyedee.me",
"audience": "https://example.com:443",
"expires": 1308859352261,
"issuer": "eyedee.me"
}
关于javascript - 在 Mozilla Persona 中登录后如何更新 loggedInUser,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15227451/