gpt4 book ai didi

Angular 2使用对象名称加入对象数组

转载 作者:太空狗 更新时间:2023-10-29 18:15:55 25 4
gpt4 key购买 nike

在我的后端,我将返回以下响应:

[
{
"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、address,但不能访问类别

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

最佳答案

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

     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>

关于Angular 2使用对象名称加入对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45337010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com