2016-09-03 69 views
1

所以我試圖通過api檢索數據並不能與密鑰選擇角2對象密鑰選擇

應用檢索/ app.component.ts

import {Component} from 'angular2/core'; 
import {Http} from 'angular2/http'; 
import {httpServiceClass} from './service'; 
import {HTTP_PROVIDERS} from 'angular2/http'; 
import {Observable} from 'rxjs/Observable'; 
import {Api} from './api'; 
@Component({ 
selector: 'my-app', 
templateUrl: 'mytemplate.html', 
providers:[httpServiceClass,HTTP_PROVIDERS] 
}) 
export class AppComponent implements OnInit{ 
private api:Api[]; 
constructor(private getservice:httpServiceClass){ 

} 


ngOnInit(){ 
this.getservice.httprequest() 
    .subscribe(data => this.api = data); 

    } 

    } 

服務文件

應用程序/應用程序.service.ts

 import {Injectable} from 'angular2/core'; 
     import {Http, HTTP_PROVIDERS} from 'angular2/http'; 
     import 'rxjs/add/operator/map'; 
     import {Observable} from 'rxjs/Observable'; 
import 'rxjs/Rx'; 
import {Api} from './api'; 

@Injectable() 
export class httpServiceClass{ 
    constructor(private http: Http){} 



    httprequest(): Observable<Api[]>{ 
     return this.http.get(' http://date.jsontest.com') 
      .map(response => response.json()); 
    } 
} 

api.ts

export interface Api{ 
    time:string; 
    date:string; 
} 

mytemplate.html

<h1 >HTTP : {{api|json}}</h1> 

返回HTTP:{ 「時間」: 「下午一時52分41秒」, 「milliseconds_since_epoch」:1472910761126, 「日期」: 「2016年9月3日」}

我試着在控制檯中鍵

<h1 >HTTP : {{api.time}}</h1> 

回報選擇

例外:找不到在[AppComponent @ 0:4中的api中]不同的支持對象'[object Object]'

+0

你在'AppComponent'中聲明'api'作爲一個數據數組:'Api []'。然後當你在模板中顯示'api | json'時,我們看到它是一個對象。你應該先修復你的代碼。 – jobou

+0

現在我很困惑我應該聲明'api'是什麼類型? –

+0

我認爲它應該在'AppComponent'和'httprequest'中都是'Api'。請注意,您並未導入「OnInit」事件。您正在導入'。/ service',但您的文件名爲'app.service.ts'。有一堆這樣的小錯誤。其他有你的錯誤的人幾乎總是在模板的某個地方使用'* ngFor'循環。你在使用它嗎? – jobou

回答

0

運行時接口在javascript世界中沒有任何東西。嘗試改變你的界面到課堂,看看它是否解決了問題。然後相應地摺疊代碼。

+0

在..之前嘗試過,沒有工作 –

+0

我會建議創建一個可以輕鬆修復的世界。 –