Angular2 Flickr JSONP [英] Angular2 Flickr JSONP
本文介绍了Angular2 Flickr JSONP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是AngularJS的新手.我正在使用Angular2制作Flickr公共供稿应用,但是遇到了这个问题.
I am very new to AngularJS. I am making a Flickr public feed app using Angular2 but I encountered this problem.
我找不到使JSONP正常工作的方法.我该怎么做才能返回JSON对象?
I couldn't find a way to get the JSONP working. What should I do to return the JSON object?
这是密码
flickr.service.ts
import { Injectable } from '@angular/core';
import { Jsonp, Http } from '@angular/http'; //use jsonp module to fetch the data from the api call
import 'rxjs/Rx'; // use rxjs as the observable
@Injectable()
export class FlickrService {
url: string;
apiKey: string = 'ffed2ef9dede27481c3195eea1be61eb';
constructor(private _jsonp: Jsonp) {
this.url = `https://api.flickr.com/services/feeds/photos_public.gne?&api_key=${this.apiKey}&per_page=12&format=json&nojsoncallback=1`;
}
getFeed() {
return this._jsonp.get(this.url)
.map(res => res.json());
}
searchTag(searchTerm: string) {
return this._jsonp.get(this.url+'&tag='+searchTerm)
.map(res => res.json());
}
}
flickr.component.ts
import { Component } from '@angular/core';
import { FlickrService } from '../services/flickr.service';
@Component({
moduleId: module.id,
selector: 'flickr',
templateUrl: './flickr.component.html'
})
export class FlickrComponent {
feedList: Array<Object>;
searchList: Array<Object>;
searchTerm: string;
constructor(private _flickrService: FlickrService) {
this._flickrService.getFeed().subscribe(res => {
console.log(res);
});
}
}
推荐答案
对于像我一样努力使它起作用的任何人,我终于在Angular 5中以以下方式使它起作用:
For anyone struggling to get this to work as I did, I finally got it to work in the following manner in Angular 5:
在app.module.ts中添加HttpClientJsonpModule
In app.module.ts add HttpClientJsonpModule
import {HttpClientModule, HttpClientJsonpModule, HttpClient} from '@angular/common/http';
imports: [
...
HttpClientModule,
HttpClientJsonpModule
...
]
在我拥有的api服务中:
in an api service I have:
getFlickrFeed() {
const url = 'https://api.flickr.com/services/feeds/photos_public.gne?format=json&id=YOUR_ID&jsoncallback=JSONP_CALLBACK';
return this.http.jsonp(url, 'JSONP_CALLBACK').pipe(
tap(
data => data
)
);
}
在我的模块中:
this.api.getFlickrFeed().subscribe(
data => {
this.flickrFeed = data['items'];
console.log(this.flickrFeed);
}
);
这篇关于Angular2 Flickr JSONP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文