我有一个在我的页面加载时触发的功能,我得到了数据
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);
});
};
});
现在我想在我的$ scope中存储userData(或authService中的res.data),但根据我的研究,我可以操作$ scope的唯一地方是我的控制器。我试图将$ scope和LoginContorller注入我的工厂和app.run并得到错误:
LoginControllerProvider< - LoginController< - AuthService
未知提供者:$ scopeProvider< - $ scope
我如何将我的请求中的值存储在$ scope中,因为我的调用是从app.run触发而不是像往常一样从任何控制器触发?
答案 0 :(得分:0)
我按照来自@ k102的评论并设法解决了我的问题,添加了以下代码片段:
1-在我的AuthService中创建了getter和setter 2-在我的API请求后设置数据 3-在控制器上将值应用于我的范围
//AuthService setters
authService.setData = function(data){
this.authData = data;
console.log(this.authData);
}
authService.getData = function(){
console.log(this.authData);
return this.authData;
}
//AuthService request
then(function successCallback(res) {
authService.setData(res.data);
//LoginController
$scope.setCurrentUser(AuthService.getData());