简体   繁体   中英

Angularjs $Resource GET Request

I'm having some problems on making a request from angular to my Java backend.

My current code is this:

$scope.listdevices=function(){
        var devices = $resource('http://localhost:8080/userapi/devices/:userId',{userId:'@userId'});
        var list=devices.query({userId:$scope.userId});
        console.log(JSON.stringify(list));
        console.log(list);
        console.log(list.length+"TAMANHO")
};

The data is being being fetched and it looks like this:

在此处输入图片说明

But the objects are not being saved in my list when I call listdevices to return a list of objects to iterate.

Thanks a lot

.query will be async, so you need a callback or a promise. Anyway, if you are trying to get a single record, you use "get". Here you have an example:

myApp.factory('Device', function($resource) {
  return $resource('http://localhost:8080/userapi/devices/:userId', {
    userId: '@userId'
  });
});

myApp.controller('YourCtrl', function(Device) {

  Device.get({
    userId: 1
  }).$promise.then(function(res){
    console.log(res)
  })
})

.query is for query your endpoint, for example if you wanted to search devices with conditions. Resource assumes that ' http://localhost:8080/userapi/devices ' will return an array, while /:userId will return an object.

Extending the answer as per your comment, if you wanted to query a list of devices of a certain users (which returns an array), you would indeed use .query

Device.query({
  userId: 1
}).$promise.then(function(results) {

  console.log(results)

})

Alternatively, if you use a callback you have access to the headers.

Device.query({
  userId: 1
}, function(results, headers) {

})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM