gpt4 book ai didi

javascript - 为什么我收到 TypeError : onSuccess is not a function in my angularjs service

转载 作者:行者123 更新时间:2023-11-28 18:07:48 25 4
gpt4 key购买 nike

我有一个 angularjs 服务,它利用 reangular 来调用电话。

angular.module('app.userSvc', [])
.factory('userSvc', ['localStorageService', '$rootScope', 'Restangular',
function(localStorageService, $rootScope, Restangular) {
function checkIfLoggedIn() {
return localStorage.getItem('token');
}

function login(email, password, onSuccess, onError) {
Restangular.all('api/authenticate')
.post({
email: email,
password: password
})
.then(
function(response) {
localStorage.setItem('token', response.token);
onSuccess(response);
},
function(response) {
onError(response);
});
}

function logout() {
localStorageService.remove('token');
}

function getCurrentToken() {
return localStorage.getItem('token');
}

function getAuthenticatedUser(onSuccess, onError) {
Restangular.one('api/authenticated_user?token=' + getCurrentToken()).get().then(function(response) {
onSuccess(response.user);
}, function(response) {
onError(response);
});
}
Restangular.setDefaultHeaders({
'Authorization': 'Bearer ' + getCurrentToken()
});
return {
checkIfLoggedIn: checkIfLoggedIn,
login: login,
logout: logout,
getCurrentToken: getCurrentToken,
getAuthenticatedUser: getAuthenticatedUser
};
}
]);

但是当我在 Controller 中调用 userSvc.getAuthenticatedUser() 方法时,我得到 TypeError: onSuccess is not a function我就是这么调用它的。

console.log(userSvc.getAuthenticatedUser());

我做错了什么。我使用的是 Angular 1.6

最佳答案

预计会出现错误,因为您的服务方法需要回调方法,因此请传递它们

function getAuthenticatedUser(onSuccess, onError){
}

所以你需要传递回调方法

userSvc.getAuthenticatedUser(function() {}, function() {})
<小时/>

或者,您可以检查参数是否已定义以及 angular.isFunction

function getAuthenticatedUser(onSuccess, onError) {
Restangular.one('api/authenticated_user?token=' + getCurrentToken()).get().then(function (response) {
!!onSuccess && angular.isFunction(onSuccess) && onSuccess(response.user);
}, function (response) {
!!onError && angular.isFunction(onError) &&
onError(response);
});
}

关于javascript - 为什么我收到 TypeError : onSuccess is not a function in my angularjs service,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42250412/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com