Use JSON data coming from WebApi in AngularJS application -
i data webapi, answer (below code datas) in json. can't access result angularjs. datas :
{ "$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 } ] }
but error below when try display result :
data.result undefined
i data :
(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 + ')'); } } }());
the controller :
(function () { angular.module('myapp') .controller('customercontroller', ['$location', '$scope', 'dataservice', customercontroller]); function customercontroller($location, $scope, dataservice) { var vm = this; vm.languages = dataservice.initformcustomer(); } }());
i think transform function gets json string have deserialize before using object... try sth like:
function transformcustomer(data, headersgetter) { var transformed = angular.fromjson(data); console.log(transformed.result[0]); return transformed.result; }
additionally may @ docs https://docs.angularjs.org/api/ng/service/$http . there code showing how append transform default 1 (that deserialization , xsrf checks)
Comments
Post a Comment