0

I’m trying to do my first http call to a 3rd party API in Angular 2 (2.1.0) that isn't just following a tutorial, and I'm pretty stuck.

I’m trying to call the Twitch API for a FreeCodeCamp challenge (which is pretty painful in itself). I’ve taken the API call from a working example that is written in jQuery, so I know I’m trying to call the right place, but I can’t seem to get the data back.

My service has the following:

apiBaseUrl: string = 'https://wind-bow.hyperdev.space/twitch-api/streams/';
user: string = 'ESL_SC2';
query: string = '?callback=?';

constructor(public jsonp: Jsonp) { }

refresh(): Observable<string> {
    const apiCall: string = this.apiBaseUrl + this.user + this.query;

    return this.jsonp.get(apiCall)
      .map((res: Response) => res.json())
      .catch((err: any) => Observable.throw(err.json().err));
}

and I’m subscribed to it in a component like this:

ngOnInit() {
    this.twitchService.refresh().subscribe(
        val => this.val = val,
        error =>  this.errorMessage = <any>error);
}

But in my console, I just have the error

Uncaught SyntaxError: Unexpected token ===

When I click on the error I get this in the Sources tab of my dev tools:

/**/ typeof  === 'function' &&
({"stream":{"_id":23623614656,"game":"StarCraft II","viewers":283,...
(etc.)

So it looks like I’m getting data back from the API, but I cannot work out why it’s not coming into my component properly. If anyone can shed any light on this, I would really appreciate it.

lordchancellor
  • 3,847
  • 4
  • 26
  • 26

1 Answers1

3

There's just one thing you need to do to get this to work. Define JSONP_CALLBACK on your querystring callback parameter:

query: string = '?callback=JSONP_CALLBACK';

You were extremely close! I found out about this here - How to make a simple JSONP asynchronous request in Angular 2?

And this is a plunker demonstrating the change and the result: http://plnkr.co/edit/QgBEcxycferSx2bTujQ6?p=preview

Community
  • 1
  • 1
silentsod
  • 8,165
  • 42
  • 40