Getting Json Data Using Jsonp From Flickr Api
I'm facing a new issue - Jsonp. I've read about and watched videos but couldn't get to the solution to fix my problem. First I'm using Angular 6. I'm trying to get a json response
Solution 1:
Since you're using Angular 6,
You'll have to import HttpClientModule, HttpClientJsonpModule
and add them to your imports
array of your Module that you want to make this call in:
...
import { HttpClientModule, HttpClientJsonpModule } from'@angular/common/http';
...
@NgModule({
imports: [..., HttpClientJsonpModule, HttpClientModule, ...],
...
})
export classAppModule { }
Then in your service, in the API URL, you'll also have to specify jsoncallback=JSONP_CALLBACK
instead of nojsoncallback=callback
:
import { Injectable } from'@angular/core';
import { HttpClient } from'@angular/common/http';
@Injectable()
exportclassPhotoService {
imagesUrl = `https://api.flickr.com/services/feeds/photos_public.gne?format=json&jsoncallback=JSONP_CALLBACK`;
constructor(private http: HttpClient) { }
getImages() {
returnthis.http.jsonp(this.imagesUrl, 'JSONP_CALLBACK');
}
}
And then in your Component:
...
import { PhotoService } from'./photo.service';
...
exportclassPhotosComponent {
myArray: any[];
constructor(private photoService: PhotoService) {
}
ngOnInit() {
this.photoService.getImages()
.subscribe((res: any) =>this.myArray = res.items);
}
}
Here's a Sample StackBlitz for your ref.
PS: You're also subscribe
ing inside getImages
which would return a Subscription
instead of an Observable
Post a Comment for "Getting Json Data Using Jsonp From Flickr Api"