【问题标题】:Use JSON data coming from WebApi in AngularJS application在 AngularJS 应用程序中使用来自 WebApi 的 JSON 数据
【发布时间】:2015-05-31 23:29:09
【问题描述】:

我从 WebApi 获取了一些数据,答案(在获取数据的代码下方)是 JSON。但我无法从 angularJS 访问这个结果。数据看起来像:

{
  "$id": "1",
  "result": [
    {
      "$id": "2",
      "name": "Français",
      "code": "FR",
      "id": 1
    },
    {
      "$id": "3",
      "name": "Néerlandais",
      "code": "NL",
      "id": 2
    },
    {
      "$id": "4",
      "name": "English",
      "code": "EN",
      "id": 3
    }
  ]
}

但是当我尝试显示结果时出现以下错误:

data.result is undefined

我得到这样的数据:

(function () {
    angular.module('myApp')
        .factory('dataService', ['$q', '$http', dataService]);

    function dataService($q, $http) {
        return {
            initFormCustomer: initFormCustomer
        };

        function initFormCustomer() {
            return $http({
                method: 'GET',
                url: 'http://localhost:123456/api/forminit/customer/',
                headers: {
                },
                transformResponse: transformCustomer,
                cache: true
            })
            .then(sendResponseData)
            .catch(sendGetCustomerError)
        }

        function sendResponseData(response) {
            return response.data;
        }

        function transformCustomer(data, headersGetter) {
            var transformed = angular.fromJson(data.result);
            console.log(data.result[0]);
            return transformed;
        }

        function sendGetCustomerError(response) {
            return $q.reject('Error retrieving customer(s). (HTTP status: ' + response.status + ')');
        }
    }
}());

控制器:

(function () {

    angular.module('myApp')
        .controller('customerController', ['$location', '$scope', 'dataService', CustomerController]);

    function CustomerController($location, $scope, dataService) {
        var vm = this;

        vm.languages = dataService.initFormCustomer();
    }

}());

【问题讨论】:

  • console.log(数据)。在收到“答案”和完成回调之间的某个地方,您正在解开它。

标签: json angularjs asp.net-web-api


【解决方案1】:

我认为 transform 函数会获取一个 json 字符串,在将其用作对象之前必须对其进行反序列化...尝试类似:

function transformCustomer(data, headersGetter) {
        var transformed = angular.fromJson(data);
        console.log(transformed.result[0]);
        return transformed.result;
    }

此外,您还可以查看文档 https://docs.angularjs.org/api/ng/service/$http 。有一些代码显示了如何将转换附加到默认转换(执行反序列化和 XSRF 检查)

【讨论】:

  • 在控制器中当我执行此操作时“var language = dataService.initFormCustomer(); alert(languages[0]);”我在控制台中得到一个未定义的“错误:[$rootScope:inprog] $digest 已经在进行中”。当我尝试这个“alert(languages.result[0]);”我得到“结果未定义”。但在 transformCustomer 中看起来还不错
  • 您在 initFormCustomer 中返回了一个承诺 - 所以您不能直接使用它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-14
  • 1970-01-01
  • 2016-04-13
相关资源
最近更新 更多