簡體   English   中英

使用ngFor在Angular中顯示來自api的剩余數據

[英]Displaying rest data from api in Angular using ngFor

我的應用程序正在使用服務通過模擬api網址引入一些數據。 我已經編寫了服務,但出現錯誤:

找不到類型為“對象”的其他支持對象“ [對象對象]”。 NgFor僅支持綁定到Iterables,例如數組。

我的JSON結構如下:

[
    "result", [
  {
    "u_serial_number": "E745K100200",
    "u_product_name": "MP2355 Black and White",
    "u_address_floor": "1",
    "u_address_line_1": "15 Rue De Cambrai",
    "u_address_post_code": "75019"
  },
  {
    "u_serial_number": "E745K100200",
    "u_product_name": "MP26789 All Colour",
    "u_address_floor": "2",
    "u_address_line_1": "14 London Road",
    "u_address_post_code": "78900"
  },
  {
    "u_serial_number": "E745K100200",
    "u_product_name": "MP2678 Black and Yellow",
    "u_address_floor": "3",
    "u_address_line_1": "13 Champs Elyses",
    "u_address_post_code": "78987"
  },
  {
    "u_serial_number": "E745K100200",
    "u_product_name": "MP7898 Black and white",
    "u_address_floor": "4",
    "u_address_line_1": "17 Rue De Cambrai",
    "u_address_post_code": "75019"
  },
  {
    "u_serial_number": "E745K100200",
    "u_product_name": "MP2355 Black and white",
    "u_address_floor": "5",
    "u_address_line_1": "11 Rue De Cambrai",
    "u_address_post_code": "75019"
  },
  {
    "u_serial_number": "E745K100200",
    "u_product_name": "MP2355 Black and white",
    "u_address_floor": "6",
    "u_address_line_1": "11 Rue De Cambrai",
    "u_address_post_code": "75019"
  },
  {
    "u_serial_number": "E745K100200",
    "u_product_name": "MP2355 Black and white",
    "u_address_floor": "7",
    "u_address_line_1": "11 Rue De Cambrai",
    "u_address_post_code": "75019"
  }
 ]
]

我在stackblitz上創建了示例: https ://stackblitz.com/edit/angular-azjsa6

您的代碼正確,但是您犯了一個小錯誤。 查看以下行。

    ngOnInit() {
            this.service.getAll().subscribe((data) => {
              this.loading = true;
              this.incidents = data['result']; // <---- this line.
              this.loading = false;
              console.log('Result - ', data);
              console.log('data is recieved');
            })
          }
        }

並且不要忘記導入HttpClient(如果正在使用)。

導入HttpModule

     import {HttpClientModule} from '@angular/common/http';

:)

您應該嘗試使用ngOnInit:

this.incidents = data.result;

分叉演示

將此添加到組件文件中

*ngFor="let incident of incidents.result"

並導入HttpModule

import {HttpClientModule} from '@angular/common/http';

暫無
暫無

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

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