0

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

9
  • 1
    Could you please share your efforts? whatever you have tried, please share that code. Commented Jun 13, 2018 at 14:34
  • 4
    You don't assign anything to an interface, since an interface is merely a type hint, and does not actually exist at runtime. You simply use your objects as they are. They fulfil the typehint of FruitsType wherever needed. Commented Jun 13, 2018 at 14:36
  • I mean, you'll need to define the result of parsing the JSON as interface whatever { fruites: FruitsType[] }, but it's already an array. Commented Jun 13, 2018 at 14:41
  • @VicJordan I did. Commented Jun 13, 2018 at 14:50
  • @deceze i am actually calling the service and do all the above code in ngonInit is that a problem? Commented Jun 13, 2018 at 14:50

4 Answers 4

2

You can assign the fruites response to any local variable you define within your component. From there it can be used to do whatever you would like as far as display or manipulating data. The interface just insures that the type is correct for the response data.

In the service you can define the type of response if you would like -

return this.http.get<FruitsType[]>(params)

That will insure that the response is an array of FruitsType objects. Then in your component where you call the service you can simply assign the response to a variable and correctly assume it will follow the FruitsType interface.

this.service.getFruit.subscribe(res => {
  this.fruites = res
})
Sign up to request clarification or add additional context in comments.

6 Comments

the thing is that my json and the interface are a bit different as you can see. the response, fruits make the output of the service identical with the interface. Is that a problem?
@user3075338 In what aspect your interface doesn't correspond to an item of your json array? Why do you say they are different?
As far as the key names not being strings with quotes around them, that's because they are becoming key names, which are not defined as an object type. The index of each object in the array is always there, so also not an issue. You should be all good!
as you may see my json is:{ "fruits": [id, name....]} while my interface does not have. but never mind. I made them identical. now i cannot access the properties of the interface to assign values! can you please advice me ?
interface.itsFiled does not work for me--gives me error that i dont know ,the field>
|
1

Here is how I get the things work, at the end:

The service to read the JSON:

  getJSON (): Observable<FruitsType[]> {
    return this.http.get<FruitsType[]>((this.configUrl))
  }

or newbiws like me, remamber you need to import the services in the app.module.ts as fallows:

import { ReadJsonService } from './services/read-json.service'

and then add it to the Providers: 

  providers: [AuthService,ReadJsonService],

here is the interface:

export interface FruitsType {

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

you can create the interface using the following command: ng generate interface NameOfTheInterface

here is how I called the service and the rest:

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


      for (const i of response) {    // this is just to see it works

        console.log('ID - ', i.id);
        console.log('Name - ', i.name);
        console.log('Selected - ', i.selected);
      }

      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("response[i].id" + response[i].id);

      }
     
    }

  }

and here is the checkbox where i use the name of fruites:

<div >
  <label for="fruits">fruits:</label>
  <div *ngFor="let fruit of fruitInterface">
    <label>
      <input type="checkbox"
             name="fruits"

      >

      {{fruit.name}}
    </label>
  </div>

</div>

HOPE IT HELPS SOME NEWBIES LIKE ME :)

Comments

0

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 enter image description here

5 Comments

i have edited the post. would you please help me reading the interface values
Here iam updated my answer. iam tested it display all value.
iam attached also output window. please up vote and mark as answer.
it gives an error saying: property json does not exist on type object
So it works fine without the convert. It actually does not need since it is already typed json as the file it read is.
0

Have you tried this?

const fruitInterface= jsonArray.map(res => (res.json() as FruitsType));

This will take each of your json objects returned from the service (that you now have in an array) and return an array of FruitTypes instead of json objects. From a bit more complicated question here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.