Angular 2使用对象的名称连接对象数组

时间:2017-07-26 20:40:58

标签: angular

在我的后端,我将回复以下回复:

[
      {
      "id": 1,
      "restaurant_name": "Ajisen Ramen Toronto",
      "description": "Japanese Restaurant",
      "phone": "416-977-8080",
      "address":       {
         "id": 3,
         "address": "332 Spadina Ave",
         "postalCode": "M5T 2G2",
         "latitude": 43.65406,
         "longitude": -79.3989,
         "city": {"city_name": "Toronto"}
      },
      "category":       [
                  {
            "id": 1,
            "categoryName": "Asian"
         },
                  {
            "id": 2,
            "categoryName": "Japanese"
         }
      ]
   }
]

现在在我的angular 2前端,我可以通过以下代码成功访问id,restaurant_name,地址,但不能访问类别

restaurant.component.html

<h3 style="color:green">Restaurant List:</h3>
<a *ngFor="let rest of restaurants" class="col-1-4">
  <div>
    <h4>Id: {{rest.id}} - Name: {{rest.restaurant_name}} - Category: {{ rest.category }} - Address: {{rest.address.address}},
      {{rest.address.city.city_name}}</h4>
  </div>
</a>

我希望我的类别部分显示如“类别:亚洲,日本”,我该怎么做?

这是 restaurant.ts

import { Address } from './address';
import { Category } from '../category';

export class Restaurant {
 categoryNames : string;
  constructor(public id: number,
    public restaurant_name: String,
    public description: String,
    public phone: String,
    public address: Address,
    public category: Category[]) {
      this.categoryNames = this.category.map(c => c.categoryName).join(',');
  };
}

我尝试访问restaurant.component.html中的categoryNames,但它没有向我返回任何信息。

这是category.ts

export class Category {
  constructor(public id: number,
              public categoryName: String) {
  }
}

有关其余代码,请参阅https://github.com/zhengye1/Eatr/tree/dev

3 个答案:

答案 0 :(得分:3)

在我的组件中,我写了下面的代码,它工作正常

     constructor(){
      let res = JSON.parse(`[
      {
      "id": 1,
      "restaurant_name": "Ajisen Ramen Toronto",
      "description": "Japanese Restaurant",
      "phone": "416-977-8080",
      "address":       {
         "id": 3,
         "address": "332 Spadina Ave",
         "postalCode": "M5T 2G2",
         "latitude": 43.65406,
         "longitude": -79.3989,
         "city": {"city_name": "Toronto"}
      },
      "category":       [
                  {
            "id": 1,
            "categoryName": "Asian"
         },
                  {
            "id": 2,
            "categoryName": "Japanese"
         }
      ]
   }
]`);
        res = res.map((res1) => {
            return new Restaurant(res1.id,
                                    res1.restaurant_name,
                                    res1.description,
                                    res1.phone,
                                    res1.category);
        });
        this.restaurants = res;
}

在我写的html中

<h3 style="color:green">Restaurant List:</h3>
<a *ngFor="let rest of restaurants" class="col-1-4">
  <div>
    <h4>Category:{{ rest.categoryNames }}</h4>
  </div>
</a>

答案 1 :(得分:2)

Restaurant课程中,您完成了以下操作:

this.categoryNames = this.category.map(c => c.categoryName).join(',');

这就是你期望

的原因
{{ rest.categoryNames }} // I assume `category` was a typo

在模板中工作,因为它不是一个数组,但是...在获取数据时,实际上你没有将传入的数据转换为Restaurant个对象的实例,你已经完成了以下工作你的http请求:

.then(response => response.json() as Restaurant[])

这不会使数组成为Restaurant个对象的数组。您需要将值映射到您的类,以真正使其成为Restaurant的数组。

嗯,可以这样做(缩短属性数量):

getRestaurants(): Promise<Restaurant[]>{
  return this.http.get(this.restaurantUrl)
  .toPromise()
  .then(response => response.json().map(x => new Restaurant(x.id, x.category)))
  .catch(this.handleError);
}

现在,您的Restaurant个对象将拥有“新”属性categoryNames,它将在模板中正常打印:)

演示: http://plnkr.co/edit/9gOzpGU9IxroSy66edmm?p=preview

答案 2 :(得分:0)

在对象中,类别是数组类型,因此您必须循环它,然后访问属性

<h3 style="color:green">Restaurant List:</h3>
<a *ngFor="let rest of restaurants" class="col-1-4">
  <div>
    <h4>Id: {{rest.id}} - Name: {{rest.restaurant_name}} - 
       Category: <span *ngFor="let cat of rest.category"> {{ cat.categoryName}}</span> - Address: {{rest.address.address}},
      {{rest.address.city.city_name}}</h4>
  </div>
</a>

您也可以使用ng-template或ng-container代替