2017-06-19 63 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