Angularjs $ location.path(' ...')不起作用

时间:2016-10-21 14:13:00

标签: angularjs location

我正在使用angularjs进行身份验证,因此在连接我的用户后,我想将他重定向到主页:

$scope.submit = function(user) {
    var request = {
        method: 'POST',
        url: 'http://localhost:9001/signIn',
        headers: {
            'Content-Type': 'application/json'
        },
        data: {
            "email": user.email,
            "password": user.password,
            "rememberMe": true
        }
    };
    $http(request).then(function(data) {
            $location.path('/home');
    }, function(error) {
        console.log(error);
    });
};

这是我的配置:

app.config(function($urlRouterProvider, $stateProvider, $httpProvider, $authProvider) {
    $urlRouterProvider.otherwise('/home');
    $stateProvider
        .state('home', {
            url: '/home',
            templateUrl: '/home',
            controller: 'HomeCtrl',
            resolve: {
                authenticated: function($q, $location, $auth) {
                    var deferred = $q.defer();

                if (!$auth.isAuthenticated()) {
                    $location.path('/signIn');
                } else {
                    deferred.resolve();
                }

                return deferred.promise;
            }
        }
    })
    .state('signIn', {
        url: '/signIn',
        templateUrl: '/signIn',
        controller: 'SignInCtrl'
    });
});

我试过了:

    $http(request).then(function(data) {
        $scope.$evalAsync(function() {
            $location.path('/home');
        });
        console.log(data);
    }, function(error) {
        console.log(error);
    });

还:

$location.path('/home');
$location.replace();

以上工作都没有,非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

... loaders: [ { test: /\.scss$/, //working, but perhaps not most modern way of autoprefixing loader: 'style-loader!css-loader!postcss-loader!sass-loader', loaders: ["style", "css", "sass"] } ], sassLoader: { includePaths: [path.resolve(__dirname, "./build")] } ... 返回false时,home状态解析程序函数无法解析或拒绝$q.defer承诺。这将导致承诺挂起并造成内存泄漏。

$auth.isAuthenticated()

在未经过身份验证时返回拒绝:

//ERRONEOUS CODE
$stateProvider
    .state('home', {
        url: '/home',
        templateUrl: '/home',
        controller: 'HomeCtrl',
        resolve: {
            authenticated: function($q, $location, $auth) {
                var deferred = $q.defer();

            if (!$auth.isAuthenticated()) {
                $location.path('/signIn');
                //FAILS to resolve or reject promise
            } else {
                deferred.resolve();
            }

            return deferred.promise;
        }
    }
})

当解析器函数返回被拒绝的承诺时,将阻止状态更改,$stateProvider .state('home', { url: '/home', templateUrl: '/home', controller: 'HomeCtrl', resolve: { authenticated: function($q, $location, $auth) { //var deferred = $q.defer(); if ($auth.isAuthenticated()) { return $q.resolve("AUTHENTICATED"); }; //otherwise return $q.reject("NOT AUTHENTICATED"); }) } }) 事件将在$stateChangeError上广播。