Javascript 在AngularUI路由器中实现中间件
情景:Javascript 在AngularUI路由器中实现中间件,javascript,angularjs,angular-ui-router,Javascript,Angularjs,Angular Ui Router,情景: 用户打开/myapp/recovery/:令牌,该令牌将调用中间件,该中间件将反过来将用户重定向到“验证”状态或“重置pwd”状态 这两个都有一个屏幕,而恢复中间件(路由器/代理/etc)不会只是重定向 如何使用ui路由器在angular 1.3中实现这样的功能 谢谢 编辑 这就是我所做的,它似乎是有效的,但我不确定这是否是最好的解决方案 config.js $stateProvider.state('account-recovery', { url: '/account-r
- 用户打开/myapp/recovery/:令牌,该令牌将调用中间件,该中间件将反过来将用户重定向到“验证”状态或“重置pwd”状态
- 这两个都有一个屏幕,而恢复中间件(路由器/代理/etc)不会只是重定向
$stateProvider.state('account-recovery', {
url: '/account-recovery/:token',
controller: 'AccountRecovery'
});
$stateProvider.state('verify', { ... });
$stateProvider.state('reset-pwd', { ... });
class AccountRecovery {
static get $inject() {
return ['$state' ...];
}
constructor($state, ...) {
this.$state = $state;
this.token = this.$state.params.token || '';
this.doSomeAsync();
}
async doSomeAsync() {
try {
const response = await getSomethingFromServer();
if (response == null || response.data == null) {
console.error('No response');
}
const user = response.data;
if (user.this) {
this.$state.go('reset-pwd');
}
else if (user.that) {
this.$state.go('verify');
}
}
catch (err) {
console.error(err);
}
}
}
而且
帐户恢复.js
$stateProvider.state('account-recovery', {
url: '/account-recovery/:token',
controller: 'AccountRecovery'
});
$stateProvider.state('verify', { ... });
$stateProvider.state('reset-pwd', { ... });
class AccountRecovery {
static get $inject() {
return ['$state' ...];
}
constructor($state, ...) {
this.$state = $state;
this.token = this.$state.params.token || '';
this.doSomeAsync();
}
async doSomeAsync() {
try {
const response = await getSomethingFromServer();
if (response == null || response.data == null) {
console.error('No response');
}
const user = response.data;
if (user.this) {
this.$state.go('reset-pwd');
}
else if (user.that) {
this.$state.go('verify');
}
}
catch (err) {
console.error(err);
}
}
}
使用主模块的运行功能:
angular
.module('myApp')
.run(runFn);
runFn.$inject = ['$rootScope', '$state', 'myService'];
function runFn($rootScope,$state, myService) {
$rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){
//In here you can use the $state service , i.e.
//if(toState.name === 'account-recovery'){
// myService.getUser().then(function(user){
// if(user){
// $state.go('reset-pwd')
// }
// else{
// $state.go('verify');
// }
//});
});
}
难道你不能在控制器中实现状态逻辑,然后根据结果,使用
$state.go()
)重定向到正确的状态吗?嗨@AlonEitan,这正是我目前正在做的(仍在进行中)但我不确定这是否是最好的解决方案。你应该在Angular JS中搜索Http拦截器,你会得到很多代码。这就像是一个中间件。公共场所。到目前为止,你所做的也是正确的。