$ location.path不起作用

Sha*_*ble 18 angularjs

当用户输入正确的用户名和密码时,我想重定向到另一个位置.但是当我$location.path('dashboard')在这里使用时,浏览器的URL被更改但是该页面没有被加载.当使用ctrl + R刷新我的页面或者点击浏览器的刷新图标然后加载适当的页面.

$http.post('/login', $scope.userInfo)
        .success(function (data) {
            //Check if the authentication was a success or a failure
            //Successful POST here does not indicate success of authentication
            if (data.status === "authentication success") {

                //Proceed to load the dashboard for the user                    
                $location.path('/dashboard');

            } else if (data.status === "authentication error") {
                //Inform user of the error
                $scope.errorMessage = data.error;
                $scope.showErrorMessage = true;
            }

        })
        .error(function (error) {
            $scope.errorMessage = "Error while attempting to authenticate. Check  log.";
            $scope.showErrorMessage = true;

        });
    };

}]);
Run Code Online (Sandbox Code Playgroud)

Raf*_*zak 24

您是否尝试过使用$ scope.$之后申请?例如.:

if(!$scope.$$phase) $scope.$apply()
Run Code Online (Sandbox Code Playgroud)

这个简短的方法也经常派上用场:

https://github.com/yearofmoo/AngularJS-Scope.SafeApply

  • 请不要盲目地使用`$ scope.$ apply`而不理解为什么.它很少是必需或有用的,因为Angular会自动在摘要中为您执行异步回调.需要应用通常意味着你已经不必要地走出Angular框架,例如使用`jQuery.ajax`而不是`$ http`,`setTimeout`而不是`$ timeout`,`onclick`而不是'ng-click `,或来自Angular外部的一些其他异步回调,已经存在一个Angular包装器. (4认同)

Don*_*ulo 14

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

"$ location服务允许您仅更改URL;它不允许您重新加载页面.当您需要更改URL并重新加载页面或导航到其他页面时,请使用较低级别的API,$ window .location.href".

因此,例如,而不是使用: $location.path("/path/to/something");

用这个: $window.location.href = "/path/to/something";

$window.location.href将更改URL 加载新页面.

希望有所帮助.


Ara*_*ind 5

如果您没有 $ scope(如果是服务),那么您可以使用

 $location.path('/path');
 if (!$rootScope.$$phase) $rootScope.$apply();
Run Code Online (Sandbox Code Playgroud)