Angular 2 join to array of objects using object name

In my backend, I will return the following response:

[
      {
      "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"
         }
      ]
   }
]

      

Now in my angular 2 frontend I can successfully access id, srcname, url but not category by following the code in

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>

      

I want my category to be displayed as "Category: Asian, Japanese", How can I do this?

Here is the restaurant.ts class

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(',');
  };
}

      

I am trying to access the categories of names in the restaurant.component.html file, but it did not return any information to me.

Here is the .ts category

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

      

For the rest of the code refer to https://github.com/zhengye1/Eatr/tree/dev

+3


source to share


3 answers


In my component i wrote below code and works fine

     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;
}

      



In html I wrote

<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>

      

+3


source


In an object, a category is an array type, so you need to code it and then access the property

<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>

      



you can also use ng-template or ng-container instead

+3


source


In your class, Restaurant

you did the following:

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

      

so you expect

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

      

work in a template since it won't be an array, but ... when fetching your data, you weren't actually using your input as object instances Restaurant

, you did the following in your http-request:

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

      

it will not cast an array to an array of objects Restaurant

. You need to map the values ​​to your class to actually make it an array Restaurant

.

Well, it can be done like this (reduced number of properties):

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);
}

      

Now your objects Restaurant

will have a "new" property categoryNames

and it will only print fine in the template :)

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

+2


source







All Articles