gpt4 book ai didi

javascript - Angular JS,工厂返回数据,但在 Controller 中它消失了

转载 作者:行者123 更新时间:2023-12-03 08:31:29 25 4
gpt4 key购买 nike

我已经开始学习一些关于 AngularJS 的知识了。我设法创建了一些简单的 Controller ,但我想做一些重构并创建一个工厂。

这是我的 js 文件之一:

angular
.module('myApp', ['ngResource'])
.factory('UserFactory', ['$http', function ($http) {
return {
getOne: function () {
$http({method: 'GET', url: 'http://localhost:8080/login/login'})
.success(function (data, status, headers, config) {
console.info(data);
return data;
})
.error(function (data, status, headers, config) {
alert("failure");
});
}
}
}])
.controller('UserController', ['$scope', 'UserFactory', function ($scope, UserFactory) {
$scope.user = UserFactory.getOne();
}]);

程序正确将从该行的 servlet 接收到的数据打印到控制台: console.info(data);
但 Controller 不会向 View 返回任何内容。我也放在这里console.info(UserFactory.getOne())它打印 undefined .

我的编码错误在哪里?

最佳答案

getOne 需要返回一个值,在本例中它将是来自 $http 的 promise 。 success 方法应该返回 Controller 所需的值。

.factory('UserFactory', ['$http', function ($http) {
return {
getOne: function () {
return $http({method: 'GET', url: 'http://localhost:8080/login/login'})
.success(function (data, status, headers, config) {
return data;
});
}
}
}]);

现在您可以在 Controller 中处理该结果。

app.controller('UserController', ['$scope', 'UserFactory', function ($scope, UserFactory) {
UserFactory.getOne().then(function(data){
$scope.user = data;
});
}]);

successfailure 方法已被弃用。您应该尝试使用 then 来代替。

.factory('UserFactory', ['$http', function ($http) {
return {
getOne: function () {
return $http({method: 'GET', url: 'http://localhost:8080/login/login'})
.then(function (response) {
return response.data;
});
}
}
}]);

关于javascript - Angular JS,工厂返回数据,但在 Controller 中它消失了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33319007/

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