Using JSON object from rest service in angularjs

2019-03-27 19:13发布

问题:

I have a rest service returning JSON with one number

{"uptime":"44"}

available under url:

http://localhost/uptime

and I want to display this value on page using angularJS.

I wrote a resource to get data from this rest url:

angular.module('utilService', ['ngResource']).
factory('UtilService', function($resource) {
    var UtilService = $resource('/uptime', { },
        {
            'get' : { method: 'GET', params: { format: '.json' } , isArray : false }
        }
    )


    UtilService.loadUptime = function(cb) {
        return UtilService.get();
    }

    return UtilService;
});

But when I use it in Controller:

angular.module('log', ['logService', 'utilService']);


function UptimeCtrl($scope, UtilService) {
    var time = UtilService.loadUptime();
    $scope.uptime = time;
}

all I see on my page is {"uptime":"44"}

I guess I need to extract/convert received object to JSON and get it 'uptime' property. but I tried JSON.parse, time.uptime, time['uptime'] and without success.

I am either doing something completely wrong or missing some basic issue here.

回答1:

$resource will just return whatever object is returned by a server, you can't really do any data pre/post processing while using $resource. But even without parsing data you should be able to display what you need. Taking your code example the {{uptime.uptime}} expression in a template should do the trick.