Angular展示含特殊命名后端JSON数据及表单使用问题
解决方案
1. 修复data字段展示问题
直接插值{{ cloudfeatures.data }}会显示[object Object],因为它是嵌套对象,可通过两种方式正确展示:
方式1:用JSON管道完整输出结构
给data字段添加json管道,就能看到完整的嵌套JSON内容:
<div> {{ cloudfeatures.data | json }} </div>
方式2:逐层访问特殊命名属性
由于属性名包含-、.、:这类特殊字符,不能用常规点语法,必须用方括号语法访问:
<!-- 展示redis.hosts --> <div>Redis地址:{{ cloudfeatures.data["Cloud-Features:CloudFeatures"]["redis.hosts"] }}</div> <!-- 展示sentinel.active状态 --> <div>Sentinel激活状态:{{ cloudfeatures.data["Cloud-Features:CloudFeatures"]["sentinel.active"] ? '是' : '否' }}</div> <!-- 遍历script.type数组 --> <div> <h3>脚本类型列表</h3> <ul> <li *ngFor="let item of cloudfeatures.data['Cloud-Features:CloudFeatures']['script.type']"> <p>名称:{{ item.name }}</p> <p>功能:{{ item.features.join('、') }}</p> </li> </ul> </div>
2. 启用类型安全(替换any类型)
组件里cloudfeatures用any会丢失类型提示,建议用你定义的Root接口约束类型:
// 组件中修改类型声明 cloudfeatures!: Root; // 服务中也指定返回类型,避免any getCloudConfig(){ return this.http.get<Root>(this.baseUrl + 'cloudfeatures'); }
3. 在表单中使用该数据(响应式表单示例)
如果要将数据绑定到表单,先初始化响应式表单,再用patchValue填充数据:
组件代码:
import { FormBuilder, FormGroup, FormArray } from '@angular/forms'; export class CloudFeaturesComponent implements OnInit { cloudfeatures!: Root; cloudForm!: FormGroup; constructor( private cloudfeatureservice: CloudFeaturesService, private titleService: Title, private fb: FormBuilder ) { this.titleService.setTitle("Cloud Features"); this.initForm(); } ngOnInit(): void { this.loadCloudFeaturesConfig(); } initForm() { this.cloudForm = this.fb.group({ redisHosts: [''], sentinelActive: [false], scriptTypes: this.fb.array([]) }); } get scriptTypes(): FormArray { return this.cloudForm.get('scriptTypes') as FormArray; } loadCloudFeaturesConfig() { this.cloudfeatureservice.getCloudConfig().subscribe(cloudfeatures => { this.cloudfeatures = cloudfeatures; this.patchFormData(); }); } patchFormData() { const coreData = this.cloudfeatures.data["Cloud-Features:CloudFeatures"]; // 填充基础字段 this.cloudForm.patchValue({ redisHosts: coreData["redis.hosts"], sentinelActive: coreData["sentinel.active"] }); // 填充脚本类型数组 this.scriptTypes.clear(); coreData["script.type"].forEach(item => { this.scriptTypes.push(this.fb.group({ name: [item.name], features: [item.features.join(', ')] })); }); } }
HTML表单代码:
<form [formGroup]="cloudForm"> <div> <label>Redis地址:</label> <input type="text" formControlName="redisHosts"> </div> <div> <label>Sentinel激活:</label> <input type="checkbox" formControlName="sentinelActive"> </div> <div formArrayName="scriptTypes"> <h3>脚本类型</h3> <div *ngFor="let script of scriptTypes.controls; let i = index" [formGroupName]="i"> <p> <label>名称:</label> <input type="text" formControlName="name"> </p> <p> <label>功能:</label> <input type="text" formControlName="features"> </p> </div> </div> </form>
内容的提问来源于stack exchange,提问作者Daan Brouwer
相关产品推荐
相关产品推荐

