簡體   English   中英

如何在Angular 2中使用ngFor迭代API數據

[英]How to iterate API data using ngFor in Angular 2

我是Angular 2的新手,我想以表格形式顯示所有API數據。 這是我的工作代碼:

http://plnkr.co/edit/CB3oGppm4fvoEExfDSRc?p=preview

但是,當我在文件中使用此代碼時,出現錯誤:

類型“ Response”不能分配給類型“ any []”

test.component.html:

<h1>{{getData[0]?.name}}</h1>
<h1>{{getData[0]?.time}}</h1>
<div *ngFor="let item of getData">
  <span>{{item?.name}}</span>
</div>

app.component.ts

import { Component } from '@angular/core';

import { ConfigurationService } from './ConfigurationService';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})

export class AppComponent {
  getData = [];

   constructor(private _ConfigurationService: ConfigurationService)
    {
        console.log("Reading _ConfigurationService ");
        //console.log(_ConfigurationService.getConfiguration());

         this._ConfigurationService.getConfiguration()
            .subscribe(
            (data)=> {
                this.getData = data; 
                console.log(this.getData);
            },
            (error) => console.log("error : " + error)
        );
    }
}

這段代碼在Plunkr中運行,但是在我的項目中嘗試時出現錯誤。 請幫助迭代我項目中的API值。 謝謝。

這是因為您尚未將類型分配給getData變量。 如果更改getData = []; to getData: any = []; ,您的代碼應該可以正常工作。 其他解決方案是更改tsconfig.json文件中的編譯器選項:

"compilerOptions": {
    "noImplicitAny": false
}

如果將noImplicitAny設置為false ,則不必為變量分配類型,如果不隱式設置變量的類型,則它將自動設置為any類型。

服務方法getConfiguration的簽名是

(): Observable<Response>

但是返回類型不正確,它應該是Observable將實現的類型。 例:

(): Observable<any[]>

您可以指定any特定類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM