【问题标题】:Unable to display interface value of array type无法显示数组类型的接口值
【发布时间】:2019-05-07 19:00:21
【问题描述】:

我有一个名为 demo 的组件,我在其中显示来自 API 的一些数据。

html

   <div  *ngFor="let  user of users">
      <p>Name: {{user?.name}}</p
      <p>Phone: {{user?.addresses}}</p
   </div>  

ts

import { Component,  Input } from '@angular/core';
import {  User} from '../app-models';

@Component({
 selector: 'wsd-demo',
  templateUrl: './demo.component.html',
  styleUrls: ['./demo.component.css'],
})

export class DemoComponent  {
 @Input()
 public users: User;
}

app-models.ts(此文件中声明的接口(用户))

 export interface User{
    name: string;
    addresses:  IAddressElement[];
 }

 export interface IAddressElement {
     type:            string;
     city:            string;
     countryOrRegion: string;
     postalCode:      string;
     state:           string;
   }

json

  "name": "Jhon",
   "addresses": [
    {
        "address": {
            "type": "Home",
            "city": "Loretto",
            "countryOrRegion": "United States",
            "postalCode": "00000",
            "state": "Minnesota",
        }
      },
      {
        "address": {
            "type": "Business",
            "city": "Norwalk",
            "countryOrRegion": "United States",
            "postalCode": "1111",
            "state": "Connecticut",
        }
      },
      {
        "address": {
            "type": "Business",
            "city": "Huntington",
            "countryOrRegion": "United States",
            "postalCode": "33333",
            "state": "West Virginia",
        }
     }
   ],

我遇到了一个问题。在 html 中,name 显示正常。但是在显示地址(即地址)时。 它显示为

[对象对象] [对象对象].

我想显示所有地址,我尝试使用 *ngFor 但没有得到确切的结果..:)

【问题讨论】:

  • json 无效
  • 怎么无效??
  • user.addresses==> 是数组,这就是为什么你得到 [object] 并且你的 json 中没有电话;)

标签: json typescript angular6


【解决方案1】:

您正在按原样打印地址数组。您必须遍历它们并打印您需要的内容。不过,我不是 Angular 的人。

<div *ngFor="let user of users">
  <p>Name: {{user?.name}}</p>
  <div *ngFor="let a of user?.addresses">
    <p>State: {{a.address.state}}</p>
  </div>
</div> 

【讨论】:

    猜你喜欢
    • 2017-12-14
    • 1970-01-01
    • 2015-05-09
    • 1970-01-01
    • 1970-01-01
    • 2020-11-09
    • 2021-07-18
    • 1970-01-01
    • 2020-09-04
    相关资源
    最近更新 更多