我正在使用Angular的最新版本,而我目前的golas是创建一个表示json对象结构的字符串数组,例如
['id','address:street','address:zipcode',..]
以下代码段是香港专业教育学院至今所取得的成就
<div *ngFor="let prop of propKeys(fetchedData)">
<div *ngIf="checkIfObject(fetchedData[prop])">
<span *ngFor="let subProp of propKeys(fetchedData[prop])" style="padding-left: 15px;">{{addToResult(prop + ':' +subProp)}}</span>
</div>
<div *ngIf="!checkIfObject(fetchedData[prop])">
<span>{{addToResult(prop)}}</span>
</div>
</div>
这是.ts文件
export class ProjectNewComponent implements OnInit {
fetchedData: any;
nestedResult: any[] = [];
constructor(private _http: HttpClient) {
this._http.get('https://jsonplaceholder.typicode.com/users')
.subscribe((data: any) => {
if(Array.isArray(data))
this.fetchedData = data[0];
else
this.fetchedData = data;
console.log(Object.keys(this.fetchedData));
})
}
ngOnInit() {}
propKeys(obj: any){
return Object.keys(obj);
}
checkIfObject(item: any){
return item instanceof Object;
}
addToResult(val: any){
this.nestedResult.push(val);
return val;
}
printResult(){
console.log(this.nestedResult);
this.nestedResult = [];
}
}
一切正常,除了单击按钮打印结果时,我看到重复的结果
['id','address:street','address:zipcode','id','address:street']
即使html输出正确
我的解决方法是更新填充该列表的功能
addToResult(val: any){
if(this.nestedResult.filter(item => item === val).length === 0)
this.nestedResult.push(val);
return val;
}
但是我不明白为什么数组有重复的值。 代码中有错误吗?