承诺后的角度状态变化
Angular state change after a promise
我不确定这是否重复,但我没有找到任何对我有用的东西,所以我发布了这个问题。
在将用户引导到特定路线之前,我需要从数据库中获取值,这样我就可以决定显示什么内容。
如果我将e.preventDefault()
移动到$state.go(..)
之前,那么它可以工作,但不能正常工作。问题是,它开始加载默认状态,当它从http获得响应时,它才重定向到main.home
。比方说,如果db请求大约需要2秒钟,那么它需要2秒钟才能重定向到main.home
,这意味着用户在大约2秒钟内看到不应该看到的内容。
有没有一种方法可以在状态更改开始时防止默认,并在状态更改结束时重定向用户?此外,如果我们可以在状态更改开始时防止默认,那么我们如何继续默认状态?
(function(){
"use strict";
angular.module('app.routes').run(['$rootScope', '$state', '$http', function($rootScope, $state, $http){
/* State change start */
$rootScope.$on('$stateChangeStart', function(e, to, toParams, from, fromParams){
e.preventDefault();
$http
.get('/url')
.error(function(err){
console.log(err);
})
.then(function(response){
if( response.data === 2 ){
// e.preventDefault()
$state.go('main.home');
}
// direct to default state
})
}
}]);
});
您可以在$stateProviderConfig中添加一个resolve
节。
在解析中,您可以向数据库发出请求并检查所需的条件。如果您不希望用户访问此页面,您可以使用$state.go()将其重定向到其他位置。
示例配置:
.state({
name: 'main.home',
template: 'index.html',
resolve: {
accessGranted: ['$http', '$state', '$q',
function($http, $state, $q) {
let deffered = $q.defer();
$http({
method: 'GET',
url: '/url'
}).then(function(data) {
if (data === 2) {
// ok to pass the user
deffered.resolve(true);
} else {
//no access, redirect
$state.go('main.unauthorized');
}
}, function(data) {
console.log(data);
//connection error, redirect
$state.go('main.unauthorized');
});
return deffered.promise;
}
]
}
});
resolve
的文档可在处获得
请注意,如果不需要支持IE ,可以使用Promise
对象而不是$q服务
处理这种情况的一种方法是添加一个拦截器,如下所示。
.config(function ($httpProvider) {
$httpProvider.interceptors.push('stateChangeInterceptor');
}).factory('stateChangeInterceptor', function ($q, $window,$rootScope) {
return {
'response': function(response) {
var isValid = true;//Write your logic here to validate the user/action.
/*
* Here you need to allow all the template urls and ajax urls which doesn't
*/
if(isValid){
return response;
}
else{
$rootScope.$broadcast("notValid",{statusCode : 'INVALID'});
}
},
'responseError': function(rejection) {
return $q.reject(rejection);
}
}
})
然后按照以下处理消息"notValid"
.run(function($state,$rootScope){
$rootScope.$on("notValid",function(event,message){
$state.transitionTo('whereever');
});
})
相关文章:
- React redux初始化功能,无论状态变化如何
- 检测Ionic中特定的应用程序状态变化
- ReactJS-这个状态中的数组在删除时被正确更新,但结果是't,直到以后的状态发生变化
- 消除淘汰中引导程序开关状态变化的歧义
- 反应组件交互和全局状态变化
- 根据单选按钮的状态变化使儿童内容出现/消失
- 观察angular ui路由器的状态变化
- 如何与Redux沟通React组件之间的UI状态变化
- html5事件监听器详细节点状态变化
- 角度/离子谷歌地图的状态变化
- ReactJS -检测状态变化的问题
- 处理ReactJs中的状态变化
- 按钮循环3个状态变化
- 每次状态变化时的离子运行函数
- FP:在没有实际状态变化的情况下反映状态
- ReactJS:如何测试状态变化
- 发生状态变化时不应用ng类
- 动态jQuery CSS具有三状态滚动背景位置根据状态变化
- 承诺后的角度状态变化
- 是否有管理事件的“量子状态变化”的有用模式?(特别是在JavaScript中)