2017-06-19 30 views
1

我对AngularJS很新。我正在使用Angular2制作一个Flickr公共提要应用程序,但我遇到了这个问题。Angular2 Flickr JSONP

我找不到让JSONP工作的方法。我该怎么做才能返回JSON对象?

enter image description here

这里的代码

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

你可以添加ngmodule代码吗? – CharanRoot

+0

你知道如何解决这个问题吗?我面临同样的问题。 –

回答

0

为了有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需求要查询的最后一个参数。但是任何和所有的文件我我曾经阅读过它,所以我刚刚完成了它,它对我来说工作得很好。

+0

我试过了,它没有工作:(有一个错误显示在控制台中。'jsonFlickrFeed'没有被定义。 – 1033

+0

'jsonFlickrFeed'不是一个函数...就像,我不知道从哪里来!您是否在附上屏幕截图或错误的完整日志? – MichaelSolati

+0

更新我的答案以获得错误处理程序,如果可能的话,也希望能从中看到日志 – MichaelSolati