我开始使用Angular JS,我正在研究我在互联网上找到的教程: http://www.sitepoint.com/user-authenication-mean-stack/
在服务中有3个未声明的变量接收函数,尽管我的研究,我仍然不理解这种语法。
代码:
register = function(user) {
return $http.post('/api/register', user).success(function(data){
saveToken(data.token);
});
};
整个服务的代码:
(function () {
angular
.module('meanApp') // service qui dépend de ce module ?
.service('authentication', authentication);
// $inject : To allow the minifiers to rename the function parameters and still be able to inject the right services, the function needs to be annotated with the $inject property. The $inject property is an array of service names to inject.
// https://docs.angularjs.org/guide/di
authentication.$inject = ['$http', '$window'];
function authentication ($http, $window) {
var saveToken = function (token) {
$window.localStorage['mean-token'] = token;
};
var getToken = function () {
return $window.localStorage['mean-token'];
};
var isLoggedIn = function() {
var token = getToken();
var payload;
if(token){
payload = token.split('.')[1];
payload = $window.atob(payload); will decode a Base64 string
payload = JSON.parse(payload);
return payload.exp > Date.now() / 1000;
} else {
return false;
}
};
var currentUser = function() {
if(isLoggedIn()){
var token = getToken();
var payload = token.split('.')[1];
payload = $window.atob(payload);
payload = JSON.parse(payload);
return {
email : payload.email,
name : payload.name
};
}
};
//An interface between the Angular app and the API, to call the login and register end-points and save the returned token. This will use the Angular $http service
register = function(user) {
return $http.post('/api/register', user).success(function(data){
saveToken(data.token);
});
};
login = function(user) {
return $http.post('/api/login', user).success(function(data) {
saveToken(data.token);
});
};
logout = function() {
$window.localStorage.removeItem('mean-token');
};
return {
currentUser : currentUser,
saveToken : saveToken,
getToken : getToken,
isLoggedIn : isLoggedIn,
register : register,
login : login,
logout : logout
};
}
})();
感谢您的解释
答案 0 :(得分:0)
Control
答案 1 :(得分:0)
此代码示例与声明其变量不一致。在声明变量时使用var
语句被认为是最佳实践,但是当不运行严格模式时,var
可以省略。
您通常应该在javascript文件的顶部使用'use strict'
,因此浏览器在严格模式下运行JS时,不允许使用未声明的变量。
类似的东西:
(function () {
'use strict';
angular
.module('meanApp') // service qui dépend de ce module ?
.service('authentication', authentication);
[...]