简体   繁体   中英

Recursively returning a JSON object from a URL list in Angular JS

I am trying to return a JSON object in my AngularJS application. I have a list of links, I have to pass them one by one, append them to an iniatal link and then grab the json file and display it.

So far even trying with one link doesn't display any result.

This is my controller:

(function () {
    'use strict';
    angular.module('index')
        .filter('resolve', function () {
                return function (x, $http) {
                    $http.get('http://FirstPartOfTheUrl.com' + x)
                        .success(function (data) {
                            return data;
                        })
                        .error(function () {
                            return 'Error Message';
                        });
                }
            }
        })
.controller('indexController', function ($scope, $http) {
    $scope.test = 'https://theUrlIHaveToAppend.com'
})();

and this is in my HTML

<div ng-controller="indexController">
    {{test | resolve}}
</div>

displaying the page just returns {{test | resolve}}

bare in mind if i try just to print the appended url it does display the correct url and if I click on that I can actually get the file. I tried AJAX and asynchronous functions but the problem remains.

as for the recursion I will apply an ng-repeat in the div but I need this to work first.

Thanks

First of all returning from callback makes no sense

$http
   .get('http://FirstPartOfTheUrl.com'+x)
   .success(function(data) {
       return data; // this makes no sense.
   });

Then your problem is actually much harder than that. Since you need to hack into angular filter infrastructure to make it work with async code.

It would be way easier to resolve in controller

controller('indexController', function ($scope, $http) {
   $http
       .get(url)
       .then(function(data){
          $scope.test = data
       });
})

But if you really need to implement this resolving feature as filters I do recommend you to use asyncFilter from this package https://github.com/cvuorinen/angular1-async-filter The code is too complex to reproduce it here. But general idea is to use $stateful filters that recalculates on every loop.

Make your resolve filter to return a promise

.filter('resolve', function($http) {
    return function(x) {
        return $http
           .get('http://FirstPartOfTheUrl.com'+x);
   }
})

And pipe it to async filter.

{{test | resolve | async}}

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