0

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:

  1. Uncaught ReferenceError: parseQuote is not defined
  2. 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.

Pawan Pillai
  • 1,955
  • 5
  • 37
  • 64

1 Answers1

1

There is nothing wrong with your code, the issue is with the api endpoint url that you are providing. Apparently it does not take the callback function name in the callback parameter but in jsonp parameter.

Replace your url with this one and it should work fine: http://api.forismatic.com/api/1.0/?method=getQuote&format=jsonp&jsonp=JSONP_CALLBACK&lang=en

Obaid
  • 1,407
  • 19
  • 36
  • Thanks Obaid. Your suggestion worked. May I ask how did you know that the callback function name needs to come in jsonp paramter and not callback parameter. Is there anything is the error which tells you this. If you can share this, it will help me in similar scenarios in future. – Pawan Pillai Jan 31 '17 at 11:07