2017-03-31 90 views
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"); 

} 

} 

上面的代碼的偉大工程這個網址https://jsonplaceholder.typicode.com/posts角2觀察到的JSON錯誤

但不與這個網址http://ergast.com/api/f1/2016/driverStandings.json

任何工作思路... TIA

+0

你可以發佈什麼樣的錯誤你好嗎?我是你把https而不是http。我測試了第二個網址,它的工作原理。 – Coyote

回答

0

阿拉汶是在正確的軌道上在這裏,但MRData情況下敏感和映射是有點關閉。這裏映射響應的正確方法應該是:

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

你的組件:

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

然後你就可以訪問數據,例如像:

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

然後,你似乎有很多嵌套的對象在你的迴應中,所以這可能會對你有所幫助:Access/process (nested) objects, arrays or JSON

這是一個演示程序,帶有mo CK JSON,但我確實嘗試了你提供的網址,並且數據收到的很好。所以複製plunker應該在你的應用程序正常工作:)

DEMO

+0

太棒了AJT_82,我會給它一個旋轉,非常感謝 – user17970

+0

沒問題,讓我知道它是如何:) – Alex

+0

那麼它是如何去? :) – Alex

0

爲了使第二您需要使用的一項工作來獲取數據

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

    } 

是原因在此working one的數據是在對象數組類型含義

enter image description here

的其中一個does not work是完全單一的對象

enter image description here

+0

謝謝,我會回報 – user17970