json - 从 json Angular 读取数据到 textarea

标签 json angular typescript

我正在尝试从本地 json 文件中读取一些测试数据,并将格式正确的数据输出到文本区域中。现在虽然它只是输出 [object Object]。我将如何获得它以便输出:

Id: theIdGoesHere

标题:theTitleGoesHere

step.service.ts 用于调用json数据的服务

public getJson(): Observable<any>{
    return this.http.get('/assets/jsonData/MyJson.json')
      .map(response => response.json());
  }

MyJson.json

{
    "data":[
        {
            "id": 1,
            "title":"Test1"
        },
        {
            "id": 2,
            "title":"Test2"
        }
    ]
}

main.componenet.ts

private testVar: any;
test(){
    this.stepService.getJson().subscribe(data => (this.testVar = data));
  }

anothermethod(){
    this.test();
    this.mainStepText = this.testVar; //mainStepText binded to textarea with [(ngModel)]="mainStepText"
}

get mainStepText2() { //Rebinded this one
   const text = [];
    const { data } = this.testVar; 

    for (let item of this.testVar.data) {
      Object.keys(item).forEach(key => {
        text.push(key + ': ' + item[key]);
      });
    }

    return text.join('\r\n'); // \r\n is the line break
  }

最佳答案

您可以使用 json 管道将对象格式化为 json 字符串:

[(ngModel)]="mainStepText | json"

如果您想显示对象的特定属性,可以在模板中访问它:

[(ngModel)]="mainStepText.data[0].title"

这将在您的字段中显示“Test1”。

关于json - 从 json Angular 读取数据到 textarea,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44393825/

相关文章:

javascript - 遍历 JSON 树并操作其数据/结构

angular - 无法导入 import { map } from 'rxjs/operators' ;

typescript - 将 Typescript 全局变量声明为 "module"类型

typescript - 构建推断对象会起作用,直到它不起作用为止

java - google-gson 读取的 JSON 的结构是什么

java - 迭代嵌套的复杂 json 对象

javascript - Microsoft AJAX 快速序列化日期

javascript - 如何在 typescript 中将新的接口(interface)类型插入数组

json - TypeScript 在对象数组上使用 forkJoin

asp.net-ajax - typescript 无法识别ajax查找功能