Search code examples
jsonangularhttpget

ANGULAR 6 http get JSON


I am having trouble getting information from certain json file.

case 1 (works):

service:

private xmlToJson: string = 'https://rss2json.com/api.json?rss_url=';

getImg(Url: string) {
return this.http.get(this.xmlToJson + Url);
}

component:

private url='https://api.flickr.com/services/feeds/photos_public.gne';

public images: any = [];

this.imgDataService.getImg(this.url)
  .subscribe(data => this.images = data);

HTML:

<h1>{{images.feed.title}}</h1>

case 2 (does not work):

service:

getImg(Url: string) {
return this.http.get(Url);
}

component:

private url = 'https://api.flickr.com/services/feeds/photos_public.gne?format=json&nojsoncallback=1';

public images: any = [];

this.imgDataService.getImg(this.url)
  .subscribe(data => this.images = data);

HTML:

<h1>{{images.title}}</h1>

Any idea why case 2 doesn't work? I ran both JSONs here: https://jsonlint.com/ and they came out valid.


Solution

  • You have a CORS error.

    Here is a StackBlitz showing the two calls and what is returned from the server. The call for the Flickr URL fails because the Flickr API doesn't (at least on this service) return headers for Access-Control-Allow-Origin to enable public access.

    Ironically, you'll be able to call the web service from any code that is not running in a web browser.

    Since you probably won't be able to convince them otherwise (others have tried), I would suggest you give up on Flickr.

    A final note: You would be able to see the error if you opened your browser's developer tools and checked the console. That should be your first stop for any weird behaviour you encounter in web development.