Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JSON object from rest service in angularjs

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.

like image 957
Tomasz Dziurko Avatar asked Oct 17 '12 19:10

Tomasz Dziurko


1 Answers

$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.

like image 71
pkozlowski.opensource Avatar answered Sep 19 '22 14:09

pkozlowski.opensource