How to view json data from angularjs http callback?

后端 未结 4 382
攒了一身酷
攒了一身酷 2020-12-21 18:26

I can see my json data in the console and I want to view it on html page after clickbutton function. From my understaning I can either do a promise ($q) or then with http o

相关标签:
4条回答
  • 2020-12-21 19:10

    $http itself is a promise, no need to create a new promise. Just return the $http.get wihoit the success written there and right the sucess fn in the controller itself. So your code will look like this:

    app.factory('httpq', function($http) {
       return {
           get: function() {
              return $http.get.apply(null, arguments);
           }
       }
    });
    

    Your controller:

    app.controller('myController',  function($scope, httpq) {
          httpq.get('http://localhost:8080/states').then(function(data) {
       $scope.returnedData = data;
     })
    
      $scope.clickButton = function() {
          $scope.returnedData;
      }
    
     });
    
    0 讨论(0)
  • 2020-12-21 19:19

    use

    $scope.returnedData=JSON.parse(data);
    

    It will give you values in JSON format

    0 讨论(0)
  • Use Ajax call

    Service:

    var demoService = angular.module('demoService', [])
    .service('myService',['$http', function($http) {
    
        this.getdata = function(entity){
            var promise = $http({
                method : 'POST',
                url : 'services/entity/add',
                data : entity,
                headers : {
                    'Content-Type' : 'application/json'
                },
                cache : false
            }).then(function (response) {
                return response;
            });
            return promise;     
        };
    }]);
    

    Controller :

    var demoService = angular.module('demoService', [])
    .controller('myctr',['$scope','myService',function($scope,myService){
       myService.getdata().then(function(response){
                //Success
    
            },function(response){
    
                //Error         
            });
    
    }]);
    

    now you can see your json in controller success

    0 讨论(0)
  • 2020-12-21 19:30

    I have not worked with promise. But your factory code seems to be ok.

    In controller declare your object first.

    If it's just object declare it as

    $scope.returnedData = {};
    

    If it's array, declare it as

    $scope.returnedData = [];
    

    The the object will not be undefined and changes will affect in HTML

    0 讨论(0)
提交回复
热议问题