0
votes

I have a problem with my application. Anyone can help me?

Error: Converting circular structure to JSON

My Service to create items and save on localstorage:

  addItem(item: Item): void {
    this.itens.unshift(item);
    let itens;
    if (localStorage.getItem('itens') == null){
      itens = [];
      itens.unshift(itens);
      localStorage.setItem('itens', JSON.stringify(itens));
    } else {
      JSON.parse(localStorage.getItem('itens'));
      itens.unshift(itens);
      localStorage.setItem('itens', JSON.stringify(itens));
    }
  }

And my component.ts:

  addItem(): void  {
    this.itemAdicionado.emit({
      nome: this.nome,
      unidade: this.unidade,
      quantidade: this.quantidade,
      preco: this.preco,
      perecivel: true,
      validade: this.validade,
      fabricacao: this.fabricacao,
    });

    this.nome = '';
    this.unidade ;
    this.quantidade ;
    this.preco;
    this.validade;
    this.fabricacao;

    console.log(this.nome, this.unidade, this.quantidade, this.preco, this.validade, this.fabricacao);
  }
2
If you add more details about error like complete stack trace that will be helpful to answer your question..Ganesh
Hi, thank you for answer but i'm begginer, if help and you want see the project has be available on my github github.com/oliveirawesley/angular6-studies , thank you so much.Wesley Oliveira
@WesleyOliveira - Welcome to stack overflow. Kindly put a detailed description of the error along with the code. It is hard to understand what problem you are facing.Ankit Sharma
@AnkitSharma Thank you so much : D This is an application for registering items and saving this data in the localstorage, however after filling in all the form data and submitting, it does not save in the localstorage appearing the error in the console: ERROR TypeError: Converting circular structure to JSON at JSON.stringify (<anonymous>)Wesley Oliveira
@WesleyOliveira - Can you create this application on stackblitz? stackblitz.comAnkit Sharma

2 Answers

0
votes

This isn't an Angular error. It's a JavaScript runtime error thrown by the JSON.stringify function. The error tells you that itens contains a circular object reference. This is OK while you run the application, but when stringifying it causes a problem: the JSON generated would become infinitely long.

As Kevin Koelzer indicated in his answer. The problem is that you wrote itens.unshift(itens);. Basically this adds the array of items to the array of items, thus creating a circular reference. Therefore, writing itens.unshift(item); instead solves your problem and is probably what you intended to do anyway.

0
votes
itens.unshift(itens);

could this be:

itens.unshift(iten);