2015-02-10 58 views
0

我想驗證用戶登錄和防止他們訪問某些路線時,在沒有登錄的情況我有以下代碼:

var isUserLoggedIn = function($q, $timeout, $http, $Location, $rootScope) { 
    // Initialize a new promise. 
    var deferred = $q.defer(); 

    // Check is user is logged in 
    $http.get('/isLoggedIn').success(function(user) { 
    if(user !== '0') { // User is logged in 
     deferred.resolve(); 
    } else { // Use is not logged in 
     $rootScope.message = 'You need to log in.'; 
     deferred.reject(); 
     $location.url('/login'); 
    } 
    }); 

    return deferred.promise; 
}; 

$routeProvider 
    .when('/', { 
    templateUrl: 'partials/index', 
    controller: 'IndexCtrl' 
    }) 
    .when('/registerUser', { 
    templateUrl: 'partials/registerUser', 
    controller: 'RegisterUserCtrl' 
    }) 
    .when('/login', { 
    templateUrl: 'partials/login', 
    controller: 'LoginCtrl' 
    }) 
    .when('/userProfile', { 
    templateUrl: 'partials/userProfile', 
    controller: 'UserProfileCtrl', 
    resolve: { 
     loggedin: isUserLoggedIn 
    } 
    }) 
    .otherwise({ 
    redirectTo: '/' 
    }); 

對於控制器我有以下內容:

angular.module('enigmaApp.controllers', []) 
.controller('UserProfileCtrl', ['$scope', 'loggedin', function($scope, loggedin) { 
    $scope.name = "john doe"; 
    $scope.loggedin = loggedin; 
}]); 

但是,當我嘗試訪問/ userProfile路由時出現以下錯誤。

錯誤:[$注射器:unpr]未知提供商:$ LocationProvider < - $位置< - 的loggedIn

通過一束放在這裏的答案的搜索後,似乎大多數人的問題是使用NG-控制器他們的觀點,但我沒有使用它。我的看法玉低於:

Layout.jade

<!DOCTYPE html> 
html(ng-app="enigmaApp", lang="en") 
    head 
     meta(charset='utf8') 
     meta(name='viewport', content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no') 
     base(href='/') 
     title Enigma base platform 
     link(rel='stylesheet', href='/css/app.css') 
     link(rel="stylesheet", href='//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css') 
    body 
     div.content-wrapper 
      block body 

index.jade

extends layout 

block body 
    div.user.f-right(ng-controller='NavCtrl') 
    a(href="/") Home 
    | | 
    a(href='/login') Login 
    | | 
    a(href='registerUser') Register 
    | | 
    a(href='/logout', target='_self') Logout 
    | | 
    a(href='/userProfile') User Profile 
    h1 Enigma Health 

    div(ng-view) 

userProfile.jade

h3 Welcome {{name}}! 
+0

您是否嘗試將'$ Location'更改爲'$ location'? – juunas 2015-02-10 04:19:18

+0

好眼睛!這是問題所在。幾小時浪費在一個國會大廈信*嘆息* – efarley 2015-02-10 04:23:29

+0

我將它添加爲答案:) – juunas 2015-02-10 04:24:12

回答

1

正如我在評論中所提到的,不斷變化的$Location$location修復了這個問題。