0
我試圖做一個JSONP呼叫採用了棱角分明2和在這個崗位跟着一切提到:How to make a simple JSONP asynchronous request in Angular 2?角2:JSONP請求給予例外:響應狀態爲:200 OK的URL
這裏是我的service.ts:
import { Injectable } from '@angular/core';
import { Http, Jsonp } from '@angular/http'
import 'rxjs';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class DataLoadService {
private quoteApiUrl: string;
constructor(private http: Http, private jsonp: Jsonp) {
this.quoteApiUrl = `http://api.forismatic.com/api/1.0/?method=getQuote&format=jsonp&jsonp=parseQuote&lang=en&callback=JSONP_CALLBACK`;
}
getQuotes(): Observable<any>{
return this.jsonp.get(this.quoteApiUrl)
.map(function(res){
return res.json() || {};
})
.catch(function(error: any){
return Observable.throw(error);
});
}
}
這該是多麼我從我的home.ts叫我getQuotes()方法:
this.dataLoadService.getQuotes()
.subscribe(data => {
console.log(data);
this.quotes.push(data);
});
這是一個JSONP調用,我在API的末尾添加了:&callback=JSONP_CALLBACK
。
當調用服務,我得到有效的JSON響應,在Chrome的開發者工具>網絡>響應標籤:
parseQuote({"quoteText":"A failure is a man who has blundered but is not capable of cashing in on the experience. ", "quoteAuthor":"Elbert Hubbard", "senderName":"", "senderLink":"", "quoteLink":"http://forismatic.com/en/d74d7833cb/"})
但我也得到了以下錯誤:
- 未捕獲的ReferenceError :未定義parseQuote
- 例外:狀態響應:200 Ok對於網址: http://api.forismatic.com/api/1.0/?method=getQuote&format=jsonp&jsonp=parseQuote&lang=en&parseQuote=ng_jsonp.__req0.finished
請指教。我正在使用angular v2.2.1。
感謝奧貝德。你的建議奏效了。我可以問你怎麼知道回調函數的名字需要來自jsonp參數而不是回調參數。有什麼是錯誤告訴你這個。如果你能分享這些,它將在未來的類似場景中幫助我。 –