使用$location.path()比较Angular中的URL

Compare URL in Angular using $location.path()

本文关键字:比较 Angular 中的 URL location path 使用      更新时间:2023-09-26

嗨,我正在尝试使用登录服务为angular.js中的单页应用程序打开某些部分(即"call.html"不执行身份验证)。

我想知道我该怎么走(http://www.example.com/app/#/call/1234)这样我就可以比较它,并重定向到"登录"页面,如果页面不是"call.html"?

我在我的app.js中有以下代码,它似乎可以工作,但在Chrome中不工作,我得到了以下错误:

TypeError: $location.path(...).contains is not a function

myapp.js.

app.run(['$rootScope', '$location', '$cookieStore', '$http',
    function ($rootScope, $location, $cookieStore, $http)
    {
        $rootScope.globals = $cookieStore.get('globals') || {};
        if ($rootScope.globals.currentUser)
        {
            $http.defaults.headers.common['Authorization'] = 'Basic' + $rootScope.globals.currentUser.authdata; // jshint ignore:line
        }
        $rootScope.$on('$locationChangeStart', function (event, next, current)
        {
            // redirect to login page if not logged in
            if($location.path().contains('call'))
            {
                return;
            }
            else
            {
                if ($location.path() !== '/login'  && !$rootScope.globals.currentUser && $location.path() !=='/')
                {
                    $location.path('/login');
                }
            }
        });
    }
]);

如有任何关于如何解决这一问题的帮助,我们将不胜感激。

contains是一个jquery方法,而不是angularjs。因此,使用这行代码:

if($location.path().contains('call')){

显然会抛出一个错误,"contains不是函数"。

您可以使用indexOf:

if($location.path().indexOf('call') > -1){

$locationProvider默认使用hashbangs(从路径/app/#/call/1234可以明显看出),因此如果不将html5Mode设置为true,则在尝试获取URL路径时会得到一个空字符串。

尝试设置$locationProvider.html5Mode(true),您应该能够获得URL路径。

您可以执行:-

var url = $location.url();
if(url.indexOf('call') > -1){
   console.log("Call present");
}