使用$ window或$ location在AngularJS中重定向

Tho*_*sen 88 javascript redirect angularjs angular-ui-router

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

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

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");
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

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

编辑(已解决):

发现了这个问题.

var landingUrl = $window.location.host + "/login";
$window.open(landingUrl, "_self");
Run Code Online (Sandbox Code Playgroud)

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

var landingUrl = "http://" + $window.location.host + "/login";
$window.location.href = landingUrl;
Run Code Online (Sandbox Code Playgroud)

它现在有效.

m.c*_*sey 78

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

编辑清晰度

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

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

window.location = "http://www.my-domain.com/login"
Run Code Online (Sandbox Code Playgroud)

  • 值得一提的是你应该使用`$ window`而不是`window`(来源:http://stackoverflow.com/questions/28906180/difference-between-window-and-window-in-ionicframework) (5认同)

Die*_*rri 36

似乎对于整页重新加载$window.location.href是首选方式.

更改浏览器URL时,不会导致整页重新加载.要在更改URL后重新加载页面,请使用较低级别的API $ window.location.href.

https://docs.angularjs.org/guide/$location


Ani*_*ngh 19

它可能对你有所帮助!演示

AngularJs代码示例

var app = angular.module('urlApp', []);
app.controller('urlCtrl', function ($scope, $log, $window) {
    $scope.ClickMeToRedirect = function () {
        var url = "http://" + $window.location.host + "/Account/Login";
        $log.log(url);
        $window.location.href = url;
    };
});
Run Code Online (Sandbox Code Playgroud)

HTML代码示例

<div ng-app="urlApp">
    <div ng-controller="urlCtrl">
        Redirect to <a href="#" ng-click="ClickMeToRedirect()">Click Me!</a>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)