1
我有,當我的頁面加載時被觸發的函數,我得到的數據在任何控制器存儲從angular.run數據
app.run
(function ($rootScope, AUTH_EVENTS, PAGES_PERMISSION, AuthService) {
$rootScope.$on('$routeChangeStart', function (event, next) {
if(!AuthService.isAuthenticated()){
var userStorage = localStorage.getItem("user_id");
if(userStorage != null){
// I want to store userData on my $scope as currentUser
var usedData = AuthService.isLogged(userStorage);
}
app.factory('AuthService', function ($http, $rootScope,Session, AUTH_EVENTS) {
var authService = {};
authService.isLogged = function (userId) {
return $http({
method: 'POST',
url: API_ROOT_SERVER_ADDRESS + "/isLogged",
headers : {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data : {userId : userId}
}).then(function successCallback(res) {
Session.create(res.data.student_id, r es.data.user_name,res.data.profile);
return res.data;
}, function errorCallback(response) {
console.log("errorCallback in response");
});
};
return authService;
})
app.controller('LoginController', function($scope, $rootScope,$routeParams,
LoginService, $location, $window, $http, AUTH_EVENTS, AuthService) {
$scope.user = {
username: "",
password : ""
};
$scope.login = function (user) {
AuthService.login(user).then(function (user) {
$rootScope.$broadcast(AUTH_EVENTS.loginSuccess);
$scope.setCurrentUser(user);
}, function() {
$rootScope.$broadcast(AUTH_EVENTS.loginFailed);
});
};
});
現在我要存儲用戶數據(或res.data在AuthService)在我的範圍內,但根據我的研究,我可以操縱$ scope的唯一地方是在我的控制器上。我試圖注入$範圍和LoginContorller對我廠和app.run並得到了有錯誤:
LoginControllerProvider < - LoginController中< - AuthService
未知提供商:$ scopeProvider < - $範圍
哪有我將來自我的請求的值存儲在$ scope中,因爲我的調用是從app.run觸發的,而不是像往常一樣從任何控制器觸發?
你應該做相反的應用在我的範圍值:在控制器 – k102
@ K102我已經擁有它注入注入'AuthService'。我剛剛用我的控制器編輯了我的問題。我如何將來自AuthService的值存儲在我的控制器上? –
'var usedData = AuthService.isLogged(userStorage);'看起來很奇怪。我會在服務中存儲'userData',所以可以從控制器訪問它,然後傳遞給作用域。 – k102