0

Unable to read the JSON returned from an API call. Here is my Services File.

import { Injectable } from '@angular/core';
import { URLSearchParams, Jsonp, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';

@Injectable()
export class BaseballService {

  constructor(private jsonp: Jsonp) {}

  search() {

    return this.jsonp.request('http://api.sportradar.us/mlb-t6/players/6e1cac5c-b059-4b80-a267-5143b19efb27/profile.json?api_key=[hidden]')
                .subscribe((data) => {
                (data)
    })}
}

which is called from here:

import { Component } from '@angular/core';
import { BaseballService } from './baseball.service'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [BaseballService]
})
export class AppComponent {
  title = 'Baseball App';

  constructor(private _baseballService: BaseballService) {

  }

  ngOnInit(){
    let zx = this._baseballService.search();
    console.log(zx);
  }
}

I can't read the JSON data and am getting this error: JSONP injected script did not invoke callback. I have tried a HTTP request but got nowhere. I tried following this example: http://plnkr.co/edit/8ap1Lm?p=preview

DeborahK
  • 57,520
  • 12
  • 104
  • 129
JohnnyBizzle
  • 971
  • 3
  • 17
  • 31
  • I haven't used JSONP with Angular, but see if the first answer here helps out a bit: https://stackoverflow.com/questions/35233604/angular-2-http-how-to-get-json-data-from-api-with-finance-charts-json-callback – Rob Zuber Jun 24 '17 at 03:00

1 Answers1

1

try this with http object

import { Injectable } from '@angular/core';
import { URLSearchParams, Jsonp, Http, Headers } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';

@Injectable()
export class BaseballService {

headers: Headers;

constructor(private http: Http) {
     this.headers = new Headers();
     this.headers.append('content-type', 'application/json');    
}

search() {

return this.http.get('http://api.sportradar.us/mlb-t6/players/6e1cac5c-b059-4b80-a267-5143b19efb27/profile.json?api_key=[hidden]',this.headers).map(resp => resp.json())   
}

and in the component

import { Component, OnInit } from '@angular/core';
import { BaseballService } from './baseball.service'

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css'],
 providers: [BaseballService]
})
export class AppComponent implements OnInit {
title = 'Baseball App';
zx: any;

 constructor(private baseballService: BaseballService) {
}

ngOnInit(){
   this.baseballService.search().subscribe((data) => {
     this.zx = data;
     console.log(this.zx);
  });

} }

alehn96
  • 1,363
  • 1
  • 13
  • 23