首先说我是AngularJS的新手,但我没有很好的经验。
我尝试做的是在路由状态下使用resolve
将用户重定向到另一个状态。我的路线状态代码是这样的:
const defaultTemplate = require('path-to-homepage-template/homepage.tpl');
module.exports = {
states: [
{
state: 'homepage',
config: {
url: '/',
templateUrl: defaultTemplate,
title: 'homepage',
controller: 'HomepageController',
controllerAs: 'homepage',
resolve: {
HomePageFormSeoResolver: 'HomePageFormSeoResolver'
}
}
}
]
};
然后我的解析器类看起来像这样:
const AngularInjected = require('app_core/angular-injected');
class HomePageFormSeoResolver extends AngularInjected {
static get $inject() {
return [
'Logger',
'CONFIG',
'$location',
'$state',
'$q'
];
}
constructor(...dependencies) {
super(...dependencies);
this._resolve();
}
/**
* Responsible to check if the the get param `formSeo` exists and it's value
* is `yes`
* @private
*/
_resolve() {
const deferred = this.deps.$q.defer();
const get_params = this.deps.$location.search();
// noinspection JSUnresolvedVariable
if (
typeof undefined !== typeof get_params.formSeo &&
'yes' === get_params.formSeo
) {
console.log('Here we are !!!!');
this.deps.$state.go('signup-confirmation');
deferred.resolve();
}
else {
deferred.resolve();
}
return deferred.promise;
}
}
module.exports = {
init: ngModule => {
ngModule.service(
'HomePageFormSeoResolver',
HomePageFormSeoResolver
);
}
};
因此,当我运行此脚本时,我在浏览器控制台中看到消息Here we are !!!!
,但重定向不起作用。
我也在同一代码博客中尝试以下语句:
deferred.reject();
或
return;
或
return false;
所以,我不知道我的案件是否有其他解决办法,或者我做错了什么。
你看错了什么吗?
(请记住,静态方法$inject()
会在类deps
属性中分配所有依赖项。)
答案 0 :(得分:0)
您可以从解析程序函数返回一个承诺,该承诺将指示是否继续导航到该状态。如果您决定在其他地方导航 - 拒绝承诺并指定正确的状态:
resolver($q, $state, $timeout, auth) {
var deferred = $q.defer();
// $timeout is an example; it also can be an xhr request or any other async function
$timeout(function() {
if (!auth.isLoggedIn()) {
// user is not logged, do not proceed
// instead, go to a different page
$state.go('noLoggedInPath');
deferred.reject();
} else {
// everything is fine, proceed
deferred.resolve();
}
});
return deferred.promise;
}
我不确定是否会对你有所帮助。