I am trying to make a JSONP call using Angular 2 and followed everything mentioned in this post: How to make a simple JSONP asynchronous request in Angular 2?
Here is my 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);
});
}
}
And this is how I am calling my getQuotes() method from my home.ts:
this.dataLoadService.getQuotes()
.subscribe(data => {
console.log(data);
this.quotes.push(data);
});
This being a JSONP call, I have added: &callback=JSONP_CALLBACK
at the end of my API.
When the service is invoked, I do get valid JSON response as in Chrome's Developer Tools > Network > Response tab:
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/"})
But I also get the following errors:
- Uncaught ReferenceError: parseQuote is not defined
- EXCEPTION: Response with status: 200 Ok for URL: http://api.forismatic.com/api/1.0/?method=getQuote&format=jsonp&jsonp=parseQuote&lang=en&parseQuote=ng_jsonp.__req0.finished
Please advise. I am using angular v2.2.1.