Reputation: 63
I have setup a quite simple web project to learn Angular2 RC3 (TypeScript). I do not have a backend at the moment and try to load several images from a JSON file with an HTTP GET request.
I have followed the official documentation on creating services and everything runs without exceptions or errors. However, the data returned from my service is always undefined despite that the HTTP GET request is completed successfully and I can see the response data in Firebug. Following is what I have done so far...
images.json file:
[
{
"description": "image1",
"file": "image1.jpeg"
},
{
"description": "image2",
"file": "image2.jpeg"
},
{
"description": "image3",
"file": "image3.jpeg"
}
]
The part of the service responsible for loading the JSON file looks like this:
import { Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
....
constructor(private http: Http) {}
getImages(imagesUrl) : Promise<Image[]> {
return this.http.get(imagesUrl)
.toPromise()
.then(response => response.json().data)
.catch(this.handleError);
};
The Image is a simple class:
export class Image {
description : string;
file : string;
}
The component that uses the service looks in part like this:
...
@Component({
...
providers : [ ImageService ]
...
})
constructor(private imageService : ImageService) {}
ngOnInit() {
this.imageService.getImages(this.imageSrcDir + "images.json")
.then(images => console.log(images))
.catch(error => console.log(error));
}
console.log(images) from above, displays undefined
I am quite puzzled as to what I did wrong, any help is really appreciated.
Upvotes: 0
Views: 2463
Reputation: 1238
The missing data attribute issue is the fundamental problem in the "Tour of Heroes" Angular2 tutorial in Part 6: https://angular.io/tutorial/toh-pt6 during the steps outlined when changing the data from a static mock to using the InMemoryDataService.
Both the getHeros() and the getHeros(id) method has this issue. Removing the '.data' part of the expression will resolve the 'undefined' result.
Upvotes: 3
Reputation: 8099
Check if
getImages(imagesUrl) : Promise<Image[]> {
return this.http.get(imagesUrl)
.toPromise()
.then(response => response.json().data)
};
has anything in response.json()
. Do something like:
.then(response => {
console.log(response.json());
return response.json().data)
})
Upvotes: 2
Reputation: 692231
Your JSON structure is an array. You're trying to acces the data
attribute of that array. But arrays don't have any data
attributes.
response.json()
is your array. No need to append .data
.
Upvotes: 8