【问题标题】:AngularJS ($http GET): $scope.names is always an empty array but call to back-end is OKAngularJS ($http GET): $scope.names 始终是一个空数组,但调用后端是可以的
【发布时间】:2020-04-14 13:59:01
【问题描述】:

调用后端(GET /app/getNames)正确返回json数组。

问题是 app.controller.js 中的 $scope.names 始终是一个空数组。

app.controller.js:

myApp.controller('myAppController', ['$scope','$http','myAppService',
        function($scope, $http, myAppService) {

            $scope.names = [];
            myAppService.getNames(function(response) {
                $scope.names = response;
            });

        } 
]);

app.service.js

myApp.service('myAppService', ['$http', function($http) {

    this.getNames= function() {
        return $http({
            method: 'GET',
            url: '/app/getNames',
         });
     }

}]);

【问题讨论】:

  • console.log(response) 有什么好处
  • 除了 Anurag 的问题,我还需要确保这个链接是正确的url: '/app/getNames', 假设 API 和前面部分在同一个主机中?
  • 使用console.log(response) I was getting nothing. Url was also correct. I managed to resolve this by changing method to myAppService.getNames().then(function(response) {...` 然后我更改了$scope.names = response.data 以仅获取必要的东西。

标签: javascript angularjs http debugging


【解决方案1】:

您服务中的getNames()-函数返回一个您忽略的承诺。您正在调用getNames()-函数并将另一个函数作为参数传递给它,这是错误的。

要获得承诺的结果,您必须将控制器中的代码更改为:

$scope.names = [];
myAppService.getNames().then(function(response) {
    $scope.names = response;
});

【讨论】:

    猜你喜欢
    • 2014-10-04
    • 1970-01-01
    • 2022-12-23
    • 2015-01-15
    • 2013-03-14
    • 2017-07-08
    • 2015-11-03
    • 2023-02-08
    • 1970-01-01
    相关资源
    最近更新 更多