gpt4 book ai didi

javascript - Angular 表现怪异 $routeChangeSuccess

转载 作者:行者123 更新时间:2023-11-30 12:45:50 25 4
gpt4 key购买 nike

所以我使用第三方库来处理我的身份验证,并在我的注销函数中调用 $location.url('/login')

但是,在我的应用程序模块中,我试图根据当前路由更改一些 CSS。执行此操作的函数如下所示:

app.run(function ($rootScope, $route) {
$rootScope.$on("$routeChangeSuccess", function(currentRoute, previousRoute){
//Change page css, based on Route information
$rootScope.isLogin = {
status: $route.current.$$route.isLogin.status
};
});
});

在我的配置中,我还指定了一些基于 ngRoute 的路由,其中​​有一个参数告诉我当前页面是否是登录页面。

    $routeProvider.
when('/route1', {
templateUrl: './partials/route1.html',
controller: 'Route1Ctrl',
isLogin: { status: false }
}).
when('/login', {
templateUrl: './partials/login.html',
controller: 'AuthCtrl',
isLogin: { status: true }
}).
otherwise({
redirectTo: '/login'
});

现在,每当我调用注销函数时,我都会收到类型错误:Cannot read property 'isLogin' of undefined,它基本上告诉我 $route.current.$$route .isLogin.status 未设置。考虑到我正在使用事件 $routeChangeSuccess 我不明白为什么它还没有被设置。

有人能看出我哪里做得不对吗?

最佳答案

实际上 'isLogin' of undefined 是说 $$routeundefined。您不应该使用以 $$ 开头的属性,因为它们是 Angular 的内部属性。在路由上定义了 isLogout 后,您可以直接通过 $route.current.isLogout 访问它。

JavaScript

angular.module('app',['ngRoute']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/route1', {
template: '<h1>Template 1</h1>',
isLogin: { status: false }
}).
when('/route2', {
template: '<h1>Template 2</h1>',
isLogin: { status: true }
}).
otherwise({
redirectTo: '/route1'
});
}]).
run(['$rootScope', function($rootScope) {
$rootScope.$on("$routeChangeSuccess", function(event, currentRoute, previousRoute){
if(!currentRoute.redirectTo) { // <= "otherwise" is a route as well, so $routeChangeSuccess is also triggered. However, it does not have `isLogin` property, so filter out this case.
$rootScope.isLogin = {
status: currentRoute.isLogin.status
};
}
});
}]);

笨蛋:http://plnkr.co/edit/R4DSz7kV56zpM9EXpNLm?p=preview

编辑:

$routeChangeSuccess 事件的处理程序接收当前路由作为第二个参数。这意味着您可以像 currentRoute.isLogin 一样直接使用它,而不是将 $route 服务注入(inject)到 run block 中并像 一样使用它$route.current.isLogin.

还有一点需要注意的是,$routeProvider的配置中的otherwise也是一条路由。因此,如果路由器将新的当前路由解析为 otherwise,也会触发 $routeChangeSuccess 事件(实际上它会被触发两次:第一次是 otherwise 路由,第二个是它重定向到的路由)。由于 otherwise 路由没有 isLogin 属性,您应该在尝试访问 currentRoute.isLogin 之前过滤掉这种情况。

关于javascript - Angular 表现怪异 $routeChangeSuccess,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22512731/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com