更具体地说,可以执行以下操作:
1.then(2或err).then(3或err).then(4或err)是直接的。
我知道有$ on('loaded',function(){How do you access loaded data from .$on('loaded') in AngularFire 0.5.0}除非它已经“加载”并且仍然缓存 和$ on('change',function(){})。 类似的东西:
$scope.$on('$firebaseAuth:login', function(){
$scope.profile = $firebase(new..);
$scope.profile.$on('loaded', function(data){
if(data.authorized === true){
$scope.private = $firebase(new..);
$scope.private.$on('loaded', function(){
var foo = $scope.private.$child('foo');
foo = 'bar';
$scope.private.$save('foo');
$scope.private.someMethod(){..}
})
}
})
})
这不是考虑错误,似乎不是最干净的做事方式。是否可以在事件中使用promise或代替$,如果是这样的话?如果没有,那么这个案例的最佳方法是什么,可以捕获任何错误?
答案 0 :(得分:0)
我的解决方案是创建返回承诺的服务,负责建立firebase引用,并处理$ q& $ on('loaded')东西。我发现这个tutorial on chaining promises很有帮助。
.service('authorizeService',['$q', '$firebase',
function($q, $firebase){
"use strict";
return{
getIsAdmin: function(profile){
var dfrd = $q.defer();
var firef = $firebase(new Firebase('https://YOURFIREBASE.firebaseio.com/profiles/' + profile));
firef.$on('loaded',function(data){
if(data === null){
dfrd.reject();
}else{
dfrd.resolve({
displayName: data.displayName,
isAdmin: data.isAdmin
});
}
});
return dfrd.promise;
}
}
}])
.service('adminService',['$q',
function($q){
"use strict";
return{
getAdmin:function(admin){
var dfrd = $q.defer();
if(admin){
dfrd.resolve({
adminWidget: 'Behold... The Adminopacalypse.'
});
}else{
dfrd.resolve({
adminWidget: 'You are not an admin.'
});
}
return dfrd.promise;
}
};
}])
控制器包含调用这些服务方法的函数,这些函数将值附加到作用域并返回链中下一个promise的对象。这些都包含在$ on('$ firebase:login)中,以便为每次新登录启动它们。
.controller('qtest', ['$rootScope','$scope', 'userQService', 'authorizeService', 'adminService', '$firebaseAuth',
function($rootScope,$scope, userQService, authorizeService, adminService, $firebaseAuth){
"use strict";
var loadAuthorizeAdmin = function(user){
return authorizeService.getIsAdmin(user)
.then(function(value){
$scope.isAdmin = value;
return value.isAdmin;
});
};
var loadAdmin = function(isAdmin){
return adminService.getAdmin(isAdmin)
.then(function(value){
$scope.adminWidget = value;
return value.adminWidget;
});
};
$rootScope.$on('$firebaseAuth:login',
function(){
var profile = $rootScope.auth.user.provider + '-' + $rootScope.auth.user.id;
$scope.user = profile;
loadAuthorizeAdmin(profile)
.then(loadAdmin);
//could be further chained
});
$rootScope.auth = $firebaseAuth(new Firebase('https://YOURFIREBASE.firebaseio.com'));
$scope.loginOne = function(){
$rootScope.auth.$login('password', {email: 'test@test.foo', password: 'test'});
}
$scope.loginTwo = function(){
$rootScope.auth.$login('password', {email: 'test2@test2.foo', password: 'test2'});
}
$scope.logout = function(){
$scope.user = null;
$scope.isAdmin = null;
$scope.adminWidget = null;
$rootScope.auth.$logout();
}
$scope.user = null;
$scope.isAdmin = null;
$scope.adminWidget = null;
}])
总有一种更好的方法但是,这有效。我没有解决错误,但这已经很久了。