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

3

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

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);
  })
}
    
asked by anonymous 02.10.2018 / 01:10

2 answers

3

Use for , this way you make sure that all items in your file are read:

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

.length will be what will for get the full size of your file and read through.

    
02.10.2018 / 01:12
2

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

It would look like this

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

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

    
02.10.2018 / 16:06