Nik*_*hil 2 javascript angularjs firebase ionic-framework ionic
我有一个firebase Auth工厂如下
app.factory("Auth", ["$firebaseAuth", "FIREBASE_URL","$ionicPlatform",
function($firebaseAuth, FIREBASE_URL, $ionicPlatform) {
var auth = {};
$ionicPlatform.ready(function(){
var ref = new Firebase(FIREBASE_URL);
auth = $firebaseAuth(ref);
});
return auth;
}
]);
Run Code Online (Sandbox Code Playgroud)
我在我的ui-router解决方案中注入Auth工厂作为依赖关系但是在配置ui-router时,auth是空的,因为平台准备就绪后开始.
app.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('menu', {
url: '/menu',
abstract:true,
cache: false,
controller: 'MenuCtrl',
templateUrl: 'templates/menu.html',
resolve: {
auth: function($state, Auth){
//<--Auth is empty here when the app starts ----->
return Auth.$requireAuth().catch(function(){
$state.go('login'); //if not authenticated send back to login
});
}
}
})
Run Code Online (Sandbox Code Playgroud)
如何确保Auth工厂在注入ui-router之前不为空?
我试过这个 -
app.factory("Auth", ["$firebaseAuth", "FIREBASE_URL","$ionicPlatform",
function($firebaseAuth, FIREBASE_URL, $ionicPlatform) {
return $ionicPlatform.ready(function(){
var ref = new Firebase(FIREBASE_URL);
return $firebaseAuth(ref);
});
}
]);
Run Code Online (Sandbox Code Playgroud)
但这会返回一个承诺,使其使用起来更加复杂.
编辑: 我在工厂使用promises来解决问题
app.factory("Auth", ["$firebaseAuth", "FIREBASE_URL","$ionicPlatform","$q",
function($firebaseAuth, FIREBASE_URL, $ionicPlatform, $q) {
var auth = {};
return {
getAuth : function(){
var d = $q.defer();
$ionicPlatform.ready().then(function(){
var ref = new Firebase(FIREBASE_URL);
auth = $firebaseAuth(ref);
d.resolve(auth);
});
return d.promise;
}
};
}
]);
Run Code Online (Sandbox Code Playgroud)
这有效但我正在寻找更好的解决方案.
你不能返回{},然后期望它神奇地成为$firebaseAuth实例,后来在异步函数中设置.对于某些异步教育,请参阅此问题.
// "points" the x variable to object A
var x = {};
// "points" the x variable to an instance of $firebaseAuth()
// but not before {} is returned from the function
x = $firebaseAuth(...)
Run Code Online (Sandbox Code Playgroud)
如果你想在运行resolve函数之前等待平台准备就绪,那么只需链接promises; 这几乎是承诺的重点.
app.factory('IonicReady', function($q, $ionicFramework) {
return $q(function(resolve, reject) {
$ionicPlatform.ready(resolve);
});
});
Run Code Online (Sandbox Code Playgroud)
然后在你的决心:
resolve: {
auth: function($state, Auth, IonicReady){
return IonicReady
.then(function() {
return Auth.$requireAuth();
})
.catch(function(e) {
console.error(e);
$state.go('login');
});
}
}
Run Code Online (Sandbox Code Playgroud)
不是一个离子专家,这简单地提出了一个问题:为什么在Ionic准备好之前根本没有引导Angular?为什么Angular在加载Ionic时不会自动引导?在平台准备好支持这一点并从门控简化过程之前,不执行任何路由似乎更合适.我不知道如何来执行的一部分,但现在看来似乎解决了X,而不是在Y.
| 归档时间: |
|
| 查看次数: |
1034 次 |
| 最近记录: |