Search code examples
angularjsdjangorestnestedrestangular

AngularJs, Django RESTful and Restangular: Consuming an array of hyperlinks


I'm having trouble configuring restangular to consume a list of api urls in my response object.

Currently, my object response looks like:

{
    folders: ['http://localhost:8000/api/folder/1', 
              'http://localhost:8000/api/folder/2',
              'http://localhost:8000/api/folder/3']
}

but i want it to return the folder objects

{
    folders: [{
                  files: ['http://localhost:8000/api/file/1'
                          'http://localhost:8000/api/file/2']
              }, 
              {
                  files: ['http://localhost:8000/api/file/3']
              },
              {
                  files: ['http://localhost:8000/api/file/4']
              }]
}

(and then eventually the file objects inside the folder objects):

{
    folders: [{
                  files: [{},{}]
              }, 
              {
                  files: [{}]
              },
              {
                  files: [{}]
              }]
}

How can I configure restangular through addResponseInterceptor or other means to consume the array of nested hyperlinks


Solution

  • I have not found a solution which performs a get() on all nested urls independently without doing it explicitly in the controller.

    So for these twice nested jsons, I created three different objects rather than one full cabinet object. Restangular than can use its put and patch methods on the objects returned.

    Then I iterate through each folder in the cabinet, and in turn each file in the folder to get all my objects into the view.

    If anybody has a better way let me know!

    vm.cabinet = {};
    vm.folders = [];
    vm.files = {}
    
    Cabinet.get(id).then(cabinetSuccessFn, errorFn);
    
    function cabinetSuccessFn(response) {
            vm.cabinet = response;
            vm.cabinet.folders.map(function(folder) {
              return Folder.get(parseInt(folder.substr(folder.lastIndexOf('/', folder.length - 2) + 1).slice(0, -1))).then(folderSuccessFn, errorFn);
            });
            vm.loading = false;
          }
    
    function folderSuccessFn(response) {
            vm.folders.push(response);
            vm.files[response.id] = [];
    
            response.files.map(function(file) {
              return Files.get(parseInt(file.substr(file.lastIndexOf('/', file.length - 2) + 1).slice(0, -1))).then(fileSuccessFn, errorFn);
            });
          }
    
    function fileSuccessFn(response) {
            vm.filess[response.folder.substr(response.folder.lastIndexOf('/', response.folder.length - 2) + 1).slice(0, -1)].push(response);
          }
    
    function errorFn(response) {
        $log.error('unable to load resource');
        $log.error(response);
    }