-1

I'm a beginner in the Angular world and I'm tempted to insert and retrieve information in ionic storage 4, however, when I try to retrieve it it returns me empty array.

I did the following

export class OcorrenciasPage implements OnInit {

  public ocorrencia: CAD231SolitacaoOcorrencia[] = new Array();
  public url = 'http://localhost:53834/api/';
  constructor(private ocorrenciaService: CAD231SolicitacaoOcorrenciaService, private storage: Storage, private http: HttpClient) {



    this.http.get(this.url + 'CAD231/').subscribe(response => {
      for (let i = 0; i < Object.keys(response).length; i++) {
        this.ocorrencia.push({
          'idSolitacaoOcorrencia': response[i]['IdSolicitacaoOCorrencia'],
          'idProvedor': response[i]['IdProvedor'],
          'idStatusOcorrencia': response[i]['IdStatusOcorrencia'],
          'idTipoSolitacaoOcorrencia': response[i]['IdTipoSolicitacaoOcorrencia'],
          'dataCadastro': response[i]['DataCadastroSolicitacao'],
          'descricaoSolicitacao': response[i]['DescricaoSolicitacao'],
          'idUsuarioCadasro': response[i]['IdUsuarioCadastro'],
          'idCliente': response[i]['IdCliente']
        });
      }
    });
    console.log(this.ocorrencia);
    this.storage.set('ocorrencias',this.ocorrencia)

    storage.get('ocorrencias').then((val) => {
      console.log(val);
    });


  }
  ngOnInit() {

  }
}

the "ocorrencia" property is being filled in correctly,

but the result comes empty, can someone explain why

Aqui está

here is the values ​​of the "occurrence" property and the value returned by the "storage"

1 Answers1

0

subscribe method is using for Observable. Which means it will fire when the object changed. For this example you are getting some data from your back-end service and your program is going to setting storage to localstorage without waiting answer from your back-end. That's why we are using Observable.

To solve this issue you have to set storage after getting your back-end response, so you have to move setting storage method inside of your subscribe. Here is the documentation for Observables

this.http.get(this.url + 'CAD231/').subscribe(response => {
  for (let i = 0; i < Object.keys(response).length; i++) {
    this.ocorrencia.push({
      'idSolitacaoOcorrencia': response[i]['IdSolicitacaoOCorrencia'],
      'idProvedor': response[i]['IdProvedor'],
      'idStatusOcorrencia': response[i]['IdStatusOcorrencia'],
      'idTipoSolitacaoOcorrencia': response[i]['IdTipoSolicitacaoOcorrencia'],
      'dataCadastro': response[i]['DataCadastroSolicitacao'],
      'descricaoSolicitacao': response[i]['DescricaoSolicitacao'],
      'idUsuarioCadasro': response[i]['IdUsuarioCadastro'],
      'idCliente': response[i]['IdCliente']
    });
  }
  console.log(this.ocorrencia);
  this.storage.set('ocorrencias',this.ocorrencia)
  storage.get('ocorrencias').then((val) => {
  console.log(val);
    });
});
nevzatopcu
  • 1,049
  • 1
  • 7
  • 13