2016-10-07 48 views
0

我想將服務注入到我的.run塊中,但注入時我無法使用它們。無法在角度js中的.run中注入服務

我的代碼是:

.run(['AuthFactory', function ($state, $rootScope, AuthFactory, $location) { 

    console.log("Auth Factory :%O", AuthFactory); 

    AuthFactory.registerUserChangeHandler(function (currentUser) { 
     $rootScope.currentUser = currentUser; 
    }); 

    AuthFactory.refresh().then(function (currentUser) { 
     console.log("Current User is", currentUser); 
    }, function (reason) { 
     // User is not Logged in 
     $location.path("login"); 

    }); 
}]); 

當我寫這篇文章的代碼,我得到錯誤:

"app.js:120Uncaught TypeError: Cannot read property 'registerUserChangeHandler' of undefined"

如果我只是在功能上則一切正常注入AuthFactory,但現在我想注入UserService &使用服務內部的方法。

我試着在功能上注入它,但我無法使用它。

對所有建議開放。

回答

0

錯誤是,如果您使用數組方式的依賴注入,則需要按照順序進行操作。例如,如果數組中的第一個值爲$ state,而不是內部控制器回調,則第一個值將表示$ state。

.run(['$state','$rootScope','AuthFactory','$location', function ($state, $rootScope, AuthFactory, $location) { 
      console.log("Auth Factory :%O", AuthFactory); 
//    UserService.login({ 
//     'username': "guest", 
//     'password': "guest" 
//    }, function() { 
//     $state.go("corporate_site.home", {reload:'true'}); 
//    }, function() { 
//     $rootScope.error = "Login Failed. Invalid Credentials."; 
//    }); 
//    $state.go("corporate_site.home", {reload: 'true'}); 

      AuthFactory.registerUserChangeHandler(function (currentUser) { 
      $rootScope.currentUser = currentUser; 
     }); 

     AuthFactory.refresh().then(function (currentUser) { 
      console.log("Current User is", currentUser); 
      }, function (reason) { 

//    User is not Logged in 
       $location.path("login"); 

      }); 
     }]); 
2

你搞砸了。

.run(['state', '$rootScope', 'AuthFactory', '$location', 
    function ($state, $rootScope, AuthFactory, $location) { 

     console.log("Auth Factory :%O", AuthFactory); 
     // ... 
    }]);