我能够弄清楚。我创建了一个新服务来处理所有的移动服务代码。由于来自客户端的方法是异步的,因此我在方法中使用了回调。我还使用 cookie 存储来保存用户的凭据对象 (currentUser),并在需要时再次将其拉出。currentUser 似乎在调用之间丢失了用户凭据对象,因此我将其存储在 cookie 中,并在丢失时将其推送到客户端。
'use strict';
angular.module('{appName}')
.factory('AzureMobileClient', ['$cookieStore', function ($cookieStore) {
var azureMobileClient = {};
azureMobileClient.isLoggedIn = false;
azureMobileClient.azureError = "";
azureMobileClient.azureMSC = new WindowsAzure.MobileServiceClient('{app URL from Azure}', '{app key from Azure}');
azureMobileClient.login = function(callback, socialMediaService) {
azureMobileClient.azureMSC.login(socialMediaService).then(function(user) {
azureMobileClient.isLoggedIn = user != null;
$cookieStore.put("azureUser", user);
callback(azureMobileClient.isLoggedIn);
}
, function(error){
alert(error);
azureMobileClient.azureError = error;
});
};
azureMobileClient.logout = function() {
azureMobileClient.getUser();
azureMobileClient.azureMSC.logout();
$cookieStore.remove("azureUser");
};
azureMobileClient.getStuff = function(callback) {
azureMobileClient.getUser();
var stuffTable = azureMobileClient.azureMSC.getTable("stuff");
stuffTable.read().then(function(items) {
callback(items);
});
};
azureMobileClient.addStuff = function(scope) {
azureMobileClient.getUser();
var stuffTable = azureMobileClient.azureMSC.getTable("stuff");
stuffTable.insert({ stuffname: scope.stuffname });
};
azureMobileClient.getUser = function() {
if (azureMobileClient.azureMSC.currentUser === null)
{
azureMobileClient.azureMSC.currentUser = $cookieStore.get("azureUser");
}
};
return azureMobileClient;
}]);
在执行登录和注销的控制器中,我这样做:
'use strict';
angular.module('{appName}')
.controller('MainCtrl', function ($scope, $window, AzureMobileClient) {
$scope.authenticate = function (socialService) {
AzureMobileClient.login(function(isLoggedIn) {
if (isLoggedIn)
{
$window.location.href = "/#/play";
}
}, socialService);
};
$scope.signOut = function() {
AzureMobileClient.logout();
}
});
登录/注销控制器的视图如下所示:
<button ng-click="signOut()">Sign Out</button>
<div class="span4">
<img src="images/facebooklogin.png" ng-click="authenticate('Facebook')" />
<img src="images/twitterlogin.png" ng-click="authenticate('Twitter')" />
<img src="images/googlelogin.png" ng-click="authenticate('Google')" />
</div>
最后在获取数据的控制器中,我这样做:
'use strict';
angular.module('{appName}')
.controller('StuffCtrl', ['$scope', '$window', 'AzureMobileClient', function ($scope, $window, AzureMobileClient) {
AzureMobileClient.getStuff(function(items) {
if (items.length == 0)
{
$window.location.href = "/#/stuff/new";
}
else
{
$scope.$apply($scope.items = items);
}
});
}]);