1
import { Injectable } from '@angular/core';
import { Http,Response } from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';


@Injectable()
export class CommentService{
private _url :string ="https://jsonplaceholder.typicode.com/posts"
   constructor(private _http:Http){}
  // method to fetch CommentS from a api service 
 getComments(){

 return this._http.get(this._url)
        .map((response:Response)=> response.json())
        .catch(this._errorHandler);

  }

  _errorHandler(error:Response){
       console.error(error);
     return Observable.throw(error ||"Server Error");

 }

}

the above code works great with this url https://jsonplaceholder.typicode.com/posts

but does not work with this url http://ergast.com/api/f1/2016/driverStandings.json

any ideas ...TIA

user17970
  • 495
  • 1
  • 9
  • 25
  • can you post what error are you getting ? my be you put https instead of http. I tested the second url and it works. – LHIOUI Mar 31 '17 at 22:52

2 Answers2

0

To make the second one work you need to get the data using

return this._http.get(this._url)
        .map((response:Response)=> response.MRDATA.json())
        .catch(this._errorHandler);

  }

Because in this working one the data is in array of objects type Meaning

enter image description here

The one which does not work is completely single object

enter image description here

Aravind
  • 40,391
  • 16
  • 91
  • 110
0

Aravind is on the right track here, but MRData case sensitive, and mapping is a bit off. The correct way to map the response here would be:

return this._http.get(this._url)
    .map((response:Response)=> response.json().MRData)
    .catch(this._errorHandler);
}

Your component:

getData() {
  this.service.getData()
    .subscribe(data => {
      this.data = data;
    });
}

Then you can access data, e.g like:

<div>
  <b>Series:</b> {{data?.series}}<br>
  <a><b>Url:</b> {{data?.url}}</a>
</div>

Then you seem to have a lot of nested objects in your response, so this might help you: Access / process (nested) objects, arrays or JSON

Here's a demo with mock JSON, but I did try that url you provided and the data was received fine. So replicating the plunker should work fine in your app :)

DEMO

Community
  • 1
  • 1
AT82
  • 71,416
  • 24
  • 140
  • 167
  • Awesome AJT_82 , I will give it a whirl, thanks a lot – user17970 Apr 03 '17 at 03:18
  • So how did it go? :) – AT82 Apr 07 '17 at 12:47
  • sorry for the late reply ..How go i drill down to a specific base node for eg "DriverStandings":[{"position":"1",... {"position":"2",.. so on and filter anything above that is it even possible – user17970 Apr 11 '17 at 06:12
  • got it to work .. finally ... thanks all .. this is the only change i made in the get request json().MRData.StandingsTable.StandingsLists[0].DriverStandings – user17970 Apr 11 '17 at 06:30