我对AngularJS很新。我正在使用Angular2创建一个Flickr公共源应用程序,但我遇到了这个问题。
我无法找到让JSONP正常工作的方法。我该怎么做才能返回JSON对象?
这里是代码
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);
});
}
}
答案 0 :(得分:2)
对于那些努力让这个像我一样工作的人,我终于让它在Angular 5中以下列方式工作:
在app.module.ts中添加HttpClientJsonpModule
class App extends Component {
constructor(props) {
super(props)
this.state = {
inputValue: "Paste your JSON here.",
outputValue: "",
hasError: false,
errorValue: ""
}
this.handleSubmit = this.handleSubmit.bind(this)
this.handleChange = this.handleChange.bind(this)
}
handleChange(event) {
this.setState({ inputValue: event.target.value })
let parsed = ""
try {
parsed = JSON.parse(this.state.inputValue)
} catch (e) {
this.setState({
hasError: true,
errorValue: e
})
return
}
const formatted = JSON.stringify(parsed, null, 2)
this.setState({
outputValue: formatted,
hasError: false,
errorValue: ""
})
}
render() {
return (
<div className="App">
<header className="App-header">
<h1 className="App-title">Formatter-tat-tat</h1>
</header>
<InputArea
value={this.state.inputValue}
handleChange={this.handleChange}
/>
<OutputArea
hasError={this.state.hasError}
value={this.state.outputValue}
error={this.state.errorValue}
/>
</div>
)
}
}
export default class InputArea extends Component {
render() {
return (
<div className="input-area">
<form>
<label>
JSON:
<textarea
value={this.props.value}
onChange={this.props.handleChange}
/>
</label>
</form>
</div>
)
}
}
export default class OutputArea extends Component {
render() {
if (this.props.hasError) {
return (
<div className="output-area">
<p>Error: {this.props.error.toString()}</p>
</div>
)
}
return (
<div className="output-area">
<pre>{this.props.value}</pre>
</div>
)
}
}
在api服务中我有:
import {HttpClientModule, HttpClientJsonpModule, HttpClient} from '@angular/common/http';
imports: [
...
HttpClientModule,
HttpClientJsonpModule
...
]
在我的模块中:
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
)
);
}
答案 1 :(得分:1)
为了让Jsonp
图书馆为我工作,我需要用callback=JSONP_CALLBACK
结束我的查询。因此,请尝试将您的服务更新为此...
import { Injectable } from '@angular/core';
import { Jsonp, Http } from '@angular/http';
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`;
}
getFeed() {
return this._jsonp.get(this.url+'&callback=JSONP_CALLBACK')
.map(res => res.json()).catch(this._handleError);
}
searchTag(searchTerm: string) {
return this._jsonp.get(this.url+'&tag='+searchTerm+'&callback=JSONP_CALLBACK')
.map(res => res.json()).catch(this._handleError);
}
private _handleError(error: Response | any) {
console.log(error);
return Observable.throw(error.code);
}
}
此外,我不能100%确定callback=JSONP_CALLBACK
是否需要作为查询的最后一个参数......但是我所有的文档都是如此曾经阅读过它,所以我刚刚完成了它,它对我来说效果很好。