How to read a JSON file dynamically? (ANGULAR 2)

Asked

Viewed 472 times

3

For example when starting I want my program to load all messages previously stored in a JSON file (message.json)

ngOnInit() {
this.emissor = 'Victor';
this._http.get<PreparacaoDeMensagem[]>("../assets/db/mensagem.json")
  .subscribe(mensagem => {
    this.mensagem = mensagem
    //console.log('o valor é ', this.mensagem);
    this.adicionarMensagem(this.mensagem);
  })
}

2 answers

3


Use the for, this way you ensure that all items in your file will be read:

for (let i = 0; i < mensagem.length; i++) {
    this.adicionarMensagem(this.mensagem[i]);
}

the .length will be what will do the for take all the size of your file and read to the end.

2

If you want something different you could use the . foreach array method

Would something like this

this.mensagem = mensagem
this.mensagem.forEach(men => {
  this.adicionarMensagem(men);
});

This method will go through the entire array and run the method for each element of the array.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.