Angular 2:如何在将json feed提供给模板之前修改它

时间:2018-01-11 14:43:54

标签: json angular

从json我得到了这个:

{
    "name": "Leonardo",
    "weapon": "sword"
},
{
    "name": "Donatello",
    "weapon": "stick"
},
{
    "name": "Michelangelo",
    "weapon": "nunchucks"
},
{
    "name": "Raphael",
    "weapon": "sai"
}

但是对于模板我想动态插入一个额外的字段:

{
    "name": "Leonardo",
    "weapon": "sword"
    "is_leader": "true"
},
{
    "name": "Donatello",
    "weapon": "stick"
    "is_leader": "false"
},
{
    "name": "Michelangelo",
    "weapon": "nunchucks"
    "is_leader": "false"
},
{
    "name": "Raphael",
    "weapon": "sai"
    "is_leader": "false"
}

但我甚至无法获得组件来返回observable(表示它未定义,但在模板中呈现正常)。到目前为止,我已经在我的组件中有这个。

constructor(private dataService: DataService) {
    this.dataSubscription = this.dataService.getTestData().subscribe(res => this.allData = res);
}

2 个答案:

答案 0 :(得分:2)

您应该修改 fetch(url, headers) .then(response => response.text()) .then(text => { resolve(this._parseResponse(text, url)); }) .catch(error => reject({ error }));

中的数据

以下是您将如何实现当前给定代码的逻辑:

.map()

答案 1 :(得分:0)

使用Angular 4.3+附带的HttpClient,您可以使用拦截器(HttpIntercept)来拦截,过滤和/或修改传入的JSON Feed。一些谷歌搜索显示如何设置拦截器并使用它们,例如here