【发布时间】:2020-06-03 20:51:25
【问题描述】:
我正在尝试使从数据库中获取的角度文本区域中的字符串更漂亮。这是我作为字符串发送并将其存储在我的数据库中的对象。我介绍了 ang-jsoneditor,但我需要验证它以防例如密钥中缺少引号。之前,我有一个 textarea,使用 angular 中的 validatorFn 进行验证非常简单。
我拥有的是这样的:
在我的 html 中:
<form fxLayout="column" [formGroup]="configForm">
<div fxFlex="1 0 auto" fxLayout="column">
<mat-form-field appearance="outline" fxFlex="100">
<mat-label>JSON File</mat-label>
<textarea matInput type="text" placeholder="Compose the json file here" formControlName="appConfig"
rows="15"></textarea>
<mat-error>
A valid JSON object is required.
</mat-error>
</mat-form-field>
</div>
</form>
这就是我的 .ts 中的内容
ngOnInit() {
this.configForm = this.formBuilder.group({
appConfig: ["", [Validators.required, this.isValidJSON]]
});
this.appManagementService.getDeviceAppConfig(this.deviceId).then(response => {
this.configErrorMessage = null;
this.lastUpdate = response.lastUpdate;
this.configForm.setValue({ appConfig: JSON.parse(response.config) });
}).catch(() => {
this.configErrorMessage = "Oops, could not get the registry info.";
});
}
private isValidJSON: ValidatorFn = (control: AbstractControl): ValidationErrors | null => {
if (!control.parent || !control) {
return null;
}
const appConfig = control.parent.get("appConfig").value;
console.log('appConfig', appConfig)
try {
JSON.parse(appConfig.toString());
return null;
} catch (error) {
return { "jsonInvalid": true };
}
}
当我传递 JSON.parse 时,它出现在我的 textarea 中的是 [object object]。我该如何解决这个问题??
【问题讨论】:
标签: angular