javascript - AngularJS: Unable to Send $Http JSON Response to View -


trying json data api , show result in view using angularjs. i'm able data correctly unable show in view. when try access object's data result undefined.

here's i'm doing...

api service:

myapp.service('apiservice', ['$http', function($http) {     var api = "http://domain.xpto/api/";      var self = this;     this.result;      var apiservice =     {         getsection: function(id)         {             var url = api + "section/" + id;              return $http.get(url);         }     }      return apiservice; }]); 

controller:

myapp.controller('maincontroller', ['$scope', '$routeparams', 'apiservice', function($scope, $routeparams, apiservice) {     apiservice.getsection(1).then(function(response)     {         $scope.$applyasync(function ()         {             var data = response.data; //json data expected             var section = data.section; //undefined?!             var images = data.images; //undefined!?              $scope.title = section.title; //undefined!?                  });     });  }]); 

json result: enter image description here

update: simplified apiservice based on @salih's , @elclanrs's suggestion.

why unable access inner objects of json (f.e, data.section.title)?

update #2: i'm able access data. seems needed data level access section object of json array (response.data.data.section). honesty don't understand why. i've accessed api using jquery , strait forward...

edit: made plunker you! http://embed.plnkr.co/yiz9tvvr4wcf3dlkz0h9/

if you, use service function update own service value. created this.result, can update value.

your service:

myapp.service('apiservice', ['$http', function($http) {     var api = "http://domain.xpto/api/";      var self = this;     this.result = {};      this.getsection = function(id){         var url = api + "section/" + id;          $http.get(url).then(function(res){             self.result = res;         });     } }]); 

i wouldn't use promise case. can access service's var controller , view.

your controller:

myapp.controller('maincontroller', ['$scope', '$routeparams', 'apiservice',  function($scope, $routeparams, apiservice) {     $scope.apiser = apiservice;      $scope.apiser.getsection(1);  }]); 

in view:

<pre>{{ apiser.result }}</pre> 

and you'll see parameter updated in real time.


Comments

Popular posts from this blog

How to understand 2 main() functions after using uftrace to profile the C++ program? -

c# - Update a combobox from a presenter (MVP) -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -