在 AngularJS 中使用 $window 或 $location 重定向 [英] Using $window or $location to Redirect in AngularJS

查看:32
本文介绍了在 AngularJS 中使用 $window 或 $location 重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发的应用程序包含各种状态(使用 ui-router),其中一些状态要求您登录,而其他状态则是公开可用的.

The app I am working on contains various states (using ui-router), where some states require you to be logged in, others are publicly available.

我创建了一个方法来有效检查用户是否登录,我目前遇到的问题实际上是在必要时重定向到我们的登录页面.需要注意的是,登录页面当前并未放置在 AngularJS 应用程序中.

I have created a method that validly checks whether a user is logged in, what I am currently having issues with is actually redirecting to our login-page when necessary. It should be noted that the login page is not currently placed within the AngularJS app.

app.run(function ($rootScope, $location, $window) {


    $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {

        if (toState.data.loginReq && !$rootScope.me.loggedIn) {
            var landingUrl = $window.location.host + "/login";
            console.log(landingUrl);
            $window.open(landingUrl, "_self");
        }
    });
});

console.log 正确显示了预期的 url.在那之后的那一行,我几乎尝试了从 $window.open 到 window.location.href 的所有内容,无论我尝试什么都没有发生重定向.

The console.log shows the intended url properly. The line after that, I have tried practically everything from $window.open to window.location.href and no matter what I've tried no redirect happens.

编辑(已解决):

发现问题.

var landingUrl = $window.location.host + "/login";
$window.open(landingUrl, "_self");

变量landingUrl 被设置为'domain.com/login',这不适用于$window.location.href (这是我尝试过的事情之一).但是在将代码更改为

The variable landingUrl was set to 'domain.com/login', which would not work with $window.location.href (which was one of the things I tried). However after changing the code to

var landingUrl = "http://" + $window.location.host + "/login";
$window.location.href = landingUrl;

现在可以使用了.

推荐答案

我相信这样做的方法是 $location.url('/RouteTo/Login');

I believe the way to do this is $location.url('/RouteTo/Login');

编辑清晰

假设我的登录视图的路线是 /Login,我会说 $location.url('/Login') 导航到该路线.

Say my route for my login view was /Login, I would say $location.url('/Login') to navigate to that route.

对于 Angular 应用之外的位置(即未定义路由),将使用普通的旧 JavaScript:

For locations outside of the Angular app (i.e. no route defined), plain old JavaScript will serve:

window.location = "http://www.my-domain.com/login"

这篇关于在 AngularJS 中使用 $window 或 $location 重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆