尝试在Angular客户端中显示数据

时间:2018-09-07 09:01:47

标签: javascript json angular typescript interface

当我尝试获取街道名称时,我得到了[object Object],在客户端显示JSON数据的最佳方法是什么。

我可以显示街道名称,但不能显示其他部分。如何检索其他元素?

//Interface 

export interface Street {
    name: string;
    color: string;
}

export interface Place {
    name: string;
    streets: Street[];
    stopLights: string[];
    similarStreets: string[];
}

// Client Side
<h2>Place List</h2>
<ul *ngFor="let place of places.places">
  <li>{{place.name}}</li>      //This works and shows the name
  <li>{{place.color}}</li>    //showing [object Object] for color

</ul>

//JSON Data 
{
  "places": [
    {
      "name": "San Jose",
      "street": [
        {
          "name": "1st Street",
          "color": "Sharkish"
        },
        {
          "name": "Santa Clara",
          "color": "49ers"
        }
     ],
  }

4 个答案:

答案 0 :(得分:2)

使用其他interface IModel { id?: number; } class Model<T extends IModel> { public data: T; constructor(data: T) { this.data = data; } } interface IConcretModel extends IModel { name: string; } class ConcretModel extends Model<IConcretModel> { static sm1() { } } let a: typeof Model; a = ConcretModel; 作为颜色

Type 'typeof ConcretModel' is not assignable to type 'typeof Model'.
  Types of parameters 'data' and 'data' are incompatible.
    Type 'T' is not assignable to type 'IConcretModel'.
      Type 'IModel' is not assignable to type 'IConcretModel'.
        Property 'name' is missing in type 'IModel'.

答案 1 :(得分:1)

您尝试显示Place对象包含在Street对象中时的“颜色”属性。此外,Place界面与您的JSON数据不匹配,因为街道在您的界面中是复数形式,而不在JSON数据中。

尝试像这样更正您的JSON数据:

//JSON Data 
{
  "places": [
    {
      "name": "San Jose",
      "streets": [
        {
          "name": "1st Street",
          "color": "Sharkish"
        },
        {
          "name": "Santa Clara",
          "color": "49ers"
        }
     ],
  }

那么您可以做:

<li *ngFor="let street of place.streets">{{ street.color }}</li>

访问您所在位置的每条街道的颜色。

答案 2 :(得分:0)

street是另一个字符串数组。因此,要访问其中的对象,您需要为其使用另一个循环(* ngFor)。

答案 3 :(得分:0)

谢谢大家!这非常有帮助!在弄脏双手后,我得到了解决方案。 这是另一个例子!

   <div>
            <ol>
                 <li *ngFor="let item of videoList" > 
                      <div>{{item.title}}</div> 
                      <ol>
                           <li *ngFor="let subItem of item.nodes"> 
                                <div>{{subItem.title}}</div> 
                           </li>
                      </ol>
                 </li>
            </ol>
       </div>


<h2>Place List</h2>
<ul *ngFor="let place of places.places"> 
  <li>{{place.name}}</li>      //This works and shows the name
  <div *ngFor="let myStreet of place.street"> 
     <li>{{ myStreet.name }} </li>
  </div>
</ul>