gpt4 book ai didi

javascript - AngularJS 服务不返回 promise

转载 作者:行者123 更新时间:2023-12-03 09:45:49 25 4
gpt4 key购买 nike

我最近开始使用 AngularJS,虽然我可以看到一些改进,但我无法理解这些 promise 。我创建了一个登录服务,它使用 Parse 框架使用户能够注册,并创建了一个注册 Controller ,将数据从表单发送到服务。由于注册需要几秒钟,我决定使用 promise 在当前用户注册后将其返回到登录 Controller 。不幸的是,我不断收到此错误:无法读取未定义的属性“then”。有人可以指出我正确的方向吗?

Controller :

(function () {
'use strict';

angular
.module('app.register')
.controller('RegisterController', RegisterController);

RegisterController.$inject = ['$q', 'logger', 'loginservice'];
/* @ngInject */
function RegisterController($q, logger, loginservice) {
var vm = this;
vm.title = 'Register';
vm.register = register;
vm.user = {
username: "",
password: "",
email: ""
};

activate();

function activate() {
logger.info('Activated Register View');
}

function register() {
var promise = loginservice.register(vm.user.username, vm.user.email, vm.user.password);

promise.then(function(userData) {
console.log("User: ", userData);
});
}
}
})();

服务:

(function() {
'use strict';

angular
.module('app.core')
.factory('loginservice', loginservice);

loginservice.$inject = ['$http', '$q', 'logger'];
/* @ngInject */
function loginservice($http, $q, logger) {
var service = {
// logIn: logIn,
// logOut: logOut,
register: register
};

return service;

function initialize() {
console.log("parse initialized");
}

function register(username, email, password) {
//alert("HELLO FROM " + username + " " + password + " " + email);

Parse.initialize(appId, parseId);
var user = new Parse.User();
user.set("username", username);
user.set("password", password);
user.set("email", email);

$http.get(user.signUp(null, {
success: function(user) {
return user;
},
error: function(user, error) {
return error.message;
// Show the error message somewhere and let the user try again.
alert("Error: " + error.code + " " + error.message);
}
})).then(function() {
return user;
});
}
}
})();

最佳答案

您只需返回 $http 调用:

function register(username, email, password) {
//alert("HELLO FROM " + username + " " + password + " " + email);

Parse.initialize(appId, parseId);
var user = new Parse.User();
user.set("username", username);
user.set("password", password);
user.set("email", email);

return $http.get(user.signUp(null, {
success: function(user) {
return user;
},
error: function(user, error) {
return error.message;
// Show the error message somewhere and let the user try again.
alert("Error: " + error.code + " " + error.message);
}
})).then(function() {
return user;
});
}

如果您不返回在 $http 调用期间创建的 Promise,则函数(默认情况下)将返回 undefined

关于javascript - AngularJS 服务不返回 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31037210/

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