1

Estoy tratando de acceder a un subarreglo JSON desde AngularJS (Angular 1), pero al parecer no encuentra los nodos del arreglo.

Código:

var app = angular.module('feedReddit', [])
app.controller('FdRditCtrl', function ($scope, $http) {
	$scope.posts = [];  

	$scope.TraeFeed = function () {
		$http({
			method: 'get',
			url: 'https://www.reddit.com/controversial/.json',
			headers: { 'Content-Type': 'text/json' }
		})
		.then(function (feeds) {
			angular.forEach(feeds.data.children, function(feed) {
				alert(1); //no imprime, no entra aquí
				$scope.posts.push(feed.data);
			});
		});
	};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller = 'FdRditCtrl'>
	<input type="button" ng-click='TraeFeed()' value="Cargar Feed" /><br/><br/>
	<div ng-repeat="post in posts">
		<h2>{{post.title}}	</h2>
	</div>
</div>

Sin embargo, no muestra el valor de los nodos. Cuando imprimo un valor en el ForEach para verificar si recorre el arreglo, no imprime nada.

El JSON es demasiado extenso para publicarlo, pero tiene esta forma:

https://www.reddit.com/controversial/.json

{
    "kind": "Listing", "data": {
        "modhash": "", "children": [{
            "kind": "t3", "data": {
                "contest_mode": false, "banned_by": null, "domain": "i.reddituploads.com",
                "subreddit": "pics", "selftext_html": null, "selftext": "", "likes":null,
                "suggested_sort": null, "user_reports": [], "secure_media": null,
                "saved": false, "id": "5qxi4e", "gilded": 0, "secure_media_embed": {},
                "clicked": false, "report_reasons": null, "author": "lidede",
                "media": null, "name": "t3_5qxi4e", "score": 0, "approved_by": null,
                "over_18": false, "removal_reason": null, "hidden": false, "preview": {
                    "images": [{
                        "source": {
"url": "https://i.redditmedia.com/MTyNB6d0XUPZtG3JoU6GB_ZAyI8AO2HzOm7jnOytBIQ.jpg" +
"?s=01b751e19d5e1d5ec9052bb932b274a8",
                            "width": 700, "height": 700
                        }, "resolutions": [{
"url": "https://i.redditmedia.com/MTyNB6d0XUPZtG3JoU6GB_ZAyI8AO2HzOm7jnOytBIQ.jpg" +
"?fit=crop&amp;crop=faces%2Centropy&amp;arh=2&amp;w=108&amp;" +
"s=99a57687775a679d9f3c816ef111121c",
                            "width": 108, "height": 108
                        }, {
"url": "https://i.redditmedia.com/MTyNB6d0XUPZtG3JoU6GB_ZAyI8AO2HzOm7jnOytBIQ.jpg" +
"?fit=crop&amp;crop=faces%2Centropy&amp;arh=2&amp;w=216&amp;" +
"s=6931c650d1b52e61c9811a8ba5f3413e",
                            "width": 216, "height": 216}, {
"url": "https://i.redditmedia.com/MTyNB6d0XUPZtG3JoU6GB_ZAyI8AO2HzOm7jnOytBIQ.jpg" +
"?fit=crop&amp;crop=faces%2Centropy&amp;arh=2&amp;w=320&amp;" +
"s=63e6f58684ed9ef1dc57c0d674b7390d",
                            "width": 320, "height": 320}, {
"url": "https://i.redditmedia.com/MTyNB6d0XUPZtG3JoU6GB_ZAyI8AO2HzOm7jnOytBIQ.jpg" +
"?fit=crop&amp;crop=faces%2Centropy&amp;arh=2&amp;w=640&amp;" +
"s=cf2daabd28b46c4e41b4106644084241",
                            "width": 640, "height": 640}],
                        "variants": {},
                        "id": "SzBl23Ng7BSluwPM-biu6_efl-KfrAvcr1TkVk_cTHQ"
                    }]
                },
"thumbnail": "http://a.thumbs.redditmedia.com/" +
"EMDnkFeuVtpS_KC_AJraNBNSCKtcRE08WOXoOaqI560.jpg",
                "subreddit_id": "t5_2qh0u", "edited": false, "link_flair_css_class": "2",
                "author_flair_css_class": null, "downs": 0, "mod_reports": [],
                "archived": false, "media_embed": {}, "post_hint": "link",
                "is_self": false, "hide_score": false, "spoiler": false,
"permalink": "/r/pics/comments/5qxi4e/and_the_winner_tshirt_of_the_week/",
                "locked": false, "stickied": false, "created": 1485766539.0,
"url": "https://i.reddituploads.com/3bf94e5b844d47028305f3afafb66692?fit=max&amp;h=1536" +
"&amp;w=1536&amp;s=5cbf342bb4a9e373001594b8790433ad",
                "author_flair_text": null, "quarantine": false,
                "title": "And the winner t-shirt of the week...",
                "created_utc": 1485737739.0, "link_flair_text": "US Politics",
                "distinguished": null, "num_comments": 45, "visited": false,
                "num_reports": null, "ups": 0
            }
        }]
    }
}
7
  • 1
    @LuisF.Elqueta no trabajes con alert, usa mejor console.log el 31 ene. 2017 a las 14:46
  • publica un codigo completo, donde esta el json? el 31 ene. 2017 a las 14:47
  • Puse el alert solo a modo de prueba para imprimir un valor del array... el 31 ene. 2017 a las 14:53
  • El codigo de arriba es angular es decir javascript, el alert me funciona sin problema si lo retrocede una linea mas arriba. el 31 ene. 2017 a las 15:04
  • 1
    si esta funcionando tu posts no veo el error el 31 ene. 2017 a las 16:35

1 respuesta 1

1

La funcion then te da los datos en la propiedad feeds.data

El json que recibes tiene este formato:

{
    "kind": "Listing",
    "data": {
        "modhash": "",
        "children": [
            {}
        ]
    }
}

Osea que feeds.data.children no existe, y lo que buscas esta en feeds.data.data.children

1
  • Amigo, no se como describir la alegria que me dio ver el resultado !! Te lo agradezco mucho. el 31 ene. 2017 a las 17:43

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.