[英]Getting JSON data using JSONP from Flickr api
我正面臨一個新問題-Jsonp。 我已閱讀並觀看了視頻,但無法解決該問題。
首先,我使用Angular6。我試圖從使用JSONP的api獲取json響應,但是當我嘗試在我的應用程序中使用它時,出現CORS錯誤。 因此,我想修復它而不必安裝chrome的CORS插件。 瀏覽器上的響應是這樣的:
jsonFlickrFeed({
"title": "Uploads from everyone",
"link": "https:\/\/www.flickr.com\/photos\/",
"description": "",
"modified": "2018-10-13T21:16:50Z",
"generator": "https:\/\/www.flickr.com",
"items": [{
"title": "photo 2504 was taken at 14:18:38",
"link": "https:\/\/www.flickr.com\/photos\/barrycorneliusox\/30359327537\/",
"media": {
"m": "https:\/\/farm2.staticflickr.com\/1944\/30359327537_fac974807d_m.jpg"
},
"date_taken": "2018-10-13T14:18:38-08:00",
"description": " <p><a href=\"https:\/\/www.flickr.com\/people\/barrycorneliusox\/\">barrycorneliusox<\/a> posted a photo:<\/p> <p><a href=\"https:\/\/www.flickr.com\/photos\/barrycorneliusox\/30359327537\/\" title=\"photo 2504 was taken at 14:18:38\"><img src=\"https:\/\/farm2.staticflickr.com\/1944\/30359327537_fac974807d_m.jpg\" width=\"240\" height=\"160\" alt=\"photo 2504 was taken at 14:18:38\" \/><\/a><\/p> <p><a href=\"http:\/\/www.oxonraces.com\/photos\/2018-10-13-oxford\/\" rel=\"nofollow\">Click here for more photos of the 2018 Chiltern XC League Match 1 - Oxford<\/a>. If you put a photo somewhere public, please add the credit <em>Photo by Barry Cornelius<\/em>.<\/p>",
"published": "2018-10-13T21:16:50Z",
"author": "nobody@flickr.com (\"barrycorneliusox\")",
"author_id": "159968055@N03",
"tags": "2018 chilternxcleaguematch1oxford oxford jsvmenpointjfirstlap barrycornelius oxonraces"
},
.....,
]
})
我的服務:(使用jsonp)
getImages() {
return this.jsonp.request(this.imagesUrl).subscribe(res => {
console.log(res);
})
}
不起作用。 我究竟做錯了什么?
我的api URL:
https://api.flickr.com/services/feeds/photos_public.gne?format=json
由於您使用的是Angular 6,
您必須導入HttpClientModule, HttpClientJsonpModule
並將它們添加到要在其中進行此調用的模塊的imports
數組中:
...
import { HttpClientModule, HttpClientJsonpModule } from '@angular/common/http';
...
@NgModule({
imports: [..., HttpClientJsonpModule, HttpClientModule, ...],
...
})
export class AppModule { }
然后在服務中的API URL中,還必須指定jsoncallback=JSONP_CALLBACK
而不是nojsoncallback=callback
:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class PhotoService {
imagesUrl = `https://api.flickr.com/services/feeds/photos_public.gne?format=json&jsoncallback=JSONP_CALLBACK`;
constructor(private http: HttpClient) { }
getImages() {
return this.http.jsonp(this.imagesUrl, 'JSONP_CALLBACK');
}
}
然后在您的組件中:
...
import { PhotoService } from './photo.service';
...
export class PhotosComponent {
myArray: any[];
constructor(private photoService: PhotoService) {
}
ngOnInit() {
this.photoService.getImages()
.subscribe((res: any) => this.myArray = res.items);
}
}
這是供您參考的示例StackBlitz 。
PS:你還subscribe
荷蘭國際集團內部getImages
這將返回一個Subscription
,而不是一個的Observable
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.