将JSON分配给类型为Interface的数组 [英] Assigning JSON to Array of type Interface

查看:148
本文介绍了将JSON分配给类型为Interface的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个有角度的项目中,我具有以下界面:

export interface FruitsType {

  id: String;
  name: String;
  selected : String;
}

并遵循JSON:

{
  [
      {"id" :"f1", "name": "apple", "selected": "false"},
      {"id": "f2" , "name":"orange", "selected": "false"}
   ]
}

目标是将水果的名称分配给复选框.

我已经使用 ngonINIT 中的服务读取了JSON文件,其输出如下:

0:{id: "f1", name: "apple", selected: "false"}
1:{id: "f2", name: "orange", selected: "false"}

我想将上述输出的ID和名称分配给接口中的相应对象,并将其推入数组. 那可能吗?怎么办?

这是我尝试过的

 // here is my service: 

 getJSON (): Observable<FruitsType[]> {
    return this.http.get<FruitsType[]>((this.configUrl))
  }
  
// and here is how i get the response:

this.jsonService.getJSON().subscribe(response => {

      // THAT WORKS FINE
      console.log("here is the forst fruit: " + response[1].name);
      console.log("here is the forst fruit: " + response[1].id);
      //console.log(response.length);


      // WANTS TO ADD THE RESPONSE TO AN INTERFACE
      for (let i=0; i<response.length; i++){
        this.fruitInterface.push({id: response[i].id, name: response[i].name, selected :  response[i].selected });
       
             }
     console.log("lenght  " +   this.fruitInterface.length);
    })



  } 

this.fruitInterface的长度为2,表示已添加值.但是我看不懂它们:(( 我这样做:this.fruitInterface.name ==>给出错误 在数组中说:this.fruitInterface [i] .name ==>无效

请帮助我

解决方案

Iam已对您的代码进行了更新,因为iam检查了一点.

这样声明的变量

public fruits: FruitsType[] = [];

这是我的方法

public getJSON() {
    this.http.get("assets/file.json")
      .subscribe(response => {                

       //here iam converting response as json
       let temp=response.json();

      //here iam getting fruits data in temp variable
        this.fruits=temp.fruites;
       //printing fruits Array.
        console.log("Fruits",this.fruits);

        //here iam newly added access in typescript file
         for(let fruit of this.fruits){
            console.log("Fruit Name",fruit.name);
         }
         console.log("Fruits access via index--->",this.fruits[0].name);
       })
  }

///此处是在html文件中新添加的访问权限

<ul *ngFor="let item of fruits">
  <li>Fruit Name :{{item.name}}</li>
  <li>Id :{{item.id}}</li>
  <li>selected :{{item.selected}}</li>
</ul>

注意:此处的结果是任何数组,因此您不能像这样直接访问. this.fruits.name (错误).

工作良好,经过iam测试,我相信它对解决您的问题很有用. 如果有任何错误,请通知我. 如果解决了问题,请标记为答案.

还附加了样品输出窗口

In a angular project, I have following interface:

export interface FruitsType {

  id: String;
  name: String;
  selected : String;
}

And following JSON:

{
  [
      {"id" :"f1", "name": "apple", "selected": "false"},
      {"id": "f2" , "name":"orange", "selected": "false"}
   ]
}

The GOAL is to assign name of the fruits to a checkbox.

I have read the JSON file using a service--in the ngonINIT-- which it's output is as follows:

0:{id: "f1", name: "apple", selected: "false"}
1:{id: "f2", name: "orange", selected: "false"}

I want to assign the id and name of above output to the corresponding in the interface and push it to an array. Is that possible? HOW?

here what I have tried

// here is my service: 

 getJSON (): Observable<FruitsType[]> {
    return this.http.get<FruitsType[]>((this.configUrl))
  }
  
// and here is how i get the response:

this.jsonService.getJSON().subscribe(response => {

      // THAT WORKS FINE
      console.log("here is the forst fruit: " + response[1].name);
      console.log("here is the forst fruit: " + response[1].id);
      //console.log(response.length);


      // WANTS TO ADD THE RESPONSE TO AN INTERFACE
      for (let i=0; i<response.length; i++){
        this.fruitInterface.push({id: response[i].id, name: response[i].name, selected :  response[i].selected });
       
             }
     console.log("lenght  " +   this.fruitInterface.length);
    })



  }

the this.fruitInterface has the lenght of 2, meaning the values has been added. BUT I CANNOT READ THEM :(( I do : this.fruitInterface.name ==> gives error in array to say: this.fruitInterface[i].name ==> does not work

PLEASE HELP ME

解决方案

Iam updated your code as little bit worked fine iam checked.

Declared variable like this

public fruits: FruitsType[] = [];

Here my method

public getJSON() {
    this.http.get("assets/file.json")
      .subscribe(response => {                

       //here iam converting response as json
       let temp=response.json();

      //here iam getting fruits data in temp variable
        this.fruits=temp.fruites;
       //printing fruits Array.
        console.log("Fruits",this.fruits);

        //here iam newly added access in typescript file
         for(let fruit of this.fruits){
            console.log("Fruit Name",fruit.name);
         }
         console.log("Fruits access via index--->",this.fruits[0].name);
       })
  }

//here iam newly added access in Html file

<ul *ngFor="let item of fruits">
  <li>Fruit Name :{{item.name}}</li>
  <li>Id :{{item.id}}</li>
  <li>selected :{{item.selected}}</li>
</ul>

Note:-here fruits is any array so you cant directly access like this. this.fruits.name (Wrong).

Working Fine iam tested i believe its useful to solve your problem. If any errror please let me know. if it is solved problem please mark as answer.

Sample output window also attached

这篇关于将JSON分配给类型为Interface的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆