Home > other >  AngularJS doesn't display json object in html after $http.get request
AngularJS doesn't display json object in html after $http.get request

Time:01-25

I'm trying to make a get request and display the json data. Here is the html div tag where the data should be displayed:

<div ng-app="app" ng-controller="searchController">
    <ul>
        <li ng-repeat="name in datas">
            {{ name }}
        </li>
    </ul>
</div>

And here is the app:

var app = angular.module('app', [

]);

app.factory('getRequest', ($http) => {
    function get() {
        return $http.get('http://localhost:8080/imagedata/')
            .then((response) => {
                console.log(response.data);
                return response.data;
            },
            (error) => {
                return error.statusText;
            });
    }

    return {
        get: get
    }
});
app.controller('searchController', ['$scope', 'getRequest', ($scope, getRequest) => {
    $scope.datas = getRequest.get();
}]);

Inside factory I have a console.log. The data is shown in console, but not in html view. I can't explain what is happening. The code should be works fine.

CodePudding user response:

It's a little hard to tell what the solution is without seeing your console data. If the data ('datas') displayed in your console is an array of objects, for example something like this...

[
    {customerId: '123', name: 'Person1', city: "Toronto"}, 
    {customerId: '456', name: 'Person2', city: "Los Angeles"},
    {customerId: '789', name: 'Person3', city: "New York"}
]

you'll want to name the specific properties, like this..

<div ng-app="app" ng-controller="searchController">
    <ul>
        <li ng-repeat="item in datas">
            {{item.name}} <--------------
            {{item.customerId}} 
            {{item.city}} 
        </li>
     </ul>
</div>

CodePudding user response:

I found the solution. As @user2864740 said, in my code I've returned the promise, not a good practice. Passing a promise into ngRepeat here is the solution

  •  Tags:  
  • Related