【问题标题】:Parsing Json that contains name value pairs in Angular 9在Angular 9中解析包含名称值对的Json
【发布时间】:2021-04-07 17:18:28
【问题描述】:

我想简单地将每个条目显示为 html 表中的一行,目前我得到以下内容

身份证 编号:1

taskFields:[object Object],[object Object],[object Object]

相反,我希望能够看到隐藏在对象 Object 中的值

我有一个角度模板

<tr *ngFor="let entry of entries | keyvalue">
  <td>{{entry.key}}:{{entry.value}}</td>
</tr>

在我的 component.ts 文件中

ngOnInit():void{
  this.entries = this.testService.getData().pipe((result) =>{
    return result
  }

在我的 testService 我有

getData() : Observable<TestEntry[]>{
return this.httpClient.get<TestEntry[]>(this.baseUrl + '/api/Test'/)
.pipe(
  catchError(error => {throw err;})
   );
}

这会返回以下数据

{"id":1,"testFields":[{"name":"test_id","value":"12345"},{"name":"testCategory", "value":"testAngular"}, {"name":"testUndefined", "value":""}]}

我的测试条目是

export interface TestEntry{
  id:string
  testFields:TestFields
}

我的测试字段是

export interface TestFields{
  name:string
  value:string
}

【问题讨论】:

    标签: arrays angular typescript ngfor


    【解决方案1】:

    如果它是一个数组,您需要遍历该值。使用以下内容:

    <table>
        <tr *ngFor="let entry of entries | keyvalue">
            <td>{{entry.key}}</td>
    
            <!-- If value is array iterate over it-->
            <ng-container *ngIf="entry.value && entry.value.length > 0; else obj">
                <td *ngFor="let inner of entry.value">{{inner.name}} : {{inner.value}}</td>
            </ng-container>
    
            <!-- If value is object display it-->
            <ng-template #obj>
                <td>{{entry.value}}</td>
            </ng-template>
        </tr>
    </table>
    

    【讨论】:

    • 哇!太棒了,效果很好,谢谢!只是想知道,如果一个条目包含一个名称值对,其值为空字符串/null。过滤掉这些的最好方法是什么?
    • 不客气。 IMO,与其用太多的结构指令(如 *ngFor、*ngIf)使模板混乱,不如过滤掉组件(.ts)本身中的数据。因此,模板将只关心渲染对象。
    • 理论上可以在 ngOnInit() .pipe 调用中完成吗?
    • 是的,可以使用 map 操作符在管道内完成。
    猜你喜欢
    • 2021-02-03
    • 1970-01-01
    • 2019-10-26
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-30
    • 1970-01-01
    相关资源
    最近更新 更多