我做了一個服務,它使用$ http發佈登錄數據並獲取身份驗證令牌,但每當我將其注入到控制器時,它就會中斷(看起來像html沒有看到它)。當我刪除服務注入,或注入一個使用$資源,而不是,一切工作正常。 下面是該服務的代碼:
MyApp.service('LoginSrv', ['$http', function User($http) {
var userData = {
isAuthenticated: false,
username: '',
bearerToken: '',
expirationDate: null,
};
function setHttpAuthHeader() {
$http.defaults.headers.common.Authorization = 'Bearer ' + userData.bearerToken;
}
this.getUserData = function(){
return userData;
};
this.authenticate = function(username, password, successCallback, errorCallback) {
var config = {
method: 'POST',
url: '/accounts/login',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
data: 'grant_type=password&username=' + username + '&password=' + password,
};
$http(config)
.success(function(data) {
userData.isAuthenticated = true;
userData.username = data.userName;
userData.bearerToken = data.access_token;
userData.expirationDate = new Date(data['.expires']);
setHttpAuthHeader();
if (typeof successCallback === 'function') {
successCallback();
}
})
.error(function(data) {
if (typeof errorCallback === 'function') {
if (data.error_description) {
errorCallback(data.error_description);
} else {
errorCallback('Unable to contact server; please, try again later.');
}
}
});
};
}]);
這裏是控制器代碼:
MyApp.controller('mainCtrl', function ($scope, LoginSrv)
{
$scope.loginUsername = 'Jan';
$scope.loginPassword = 'Maria';
$scope.userLogin = new LoginSrv();
$scope.loginError = false;
function onSuccesfulLogin() {};
function onFailedLogin(error) {};
$scope.login = function() {
userLogin.authenticate($scope.loginUsername, $scope.loginPassword, onSuccesfulLogin, onFailedLogin);
};
});
什麼錯誤,你接受?你是什麼意思html沒有看到它? – user2954587
爲什麼你要做'功能用戶($ http)'而不是'function($ http)'? – RPGillespie
另外你爲什麼混合注射樣式?在您的控制器中,您正在使用直接注射,但在您的服務中,您正在使用小型化注射。 – RPGillespie