Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

214
Visualizações
Listing items from Ionic 2 Storage

I have the below Home.ts which calls a service, ProductService.ts to get me a list of objects from Storage which I render on home.html.

export class HomePage {

  products;

  constructor(public navCtrl: NavController, private productService: ProductService, private storage : Storage) {    

  }

  ngOnInit(){           
    this.productService.fetchProducts();           
    this.products = this.productService.products;           
  }
}

export class ProductService{
  fetchProducts(){
      this.storage.get('products') // returns a promise which returns data or error
        .then(
          (products) => {
            products? this.products = products : this.products = [];                      
        })  
        .catch(
          err => console.log(err)
        );  
  }
}

The listing doesn't work and i get a blank page. But if I copy the code from the ProductService and paste it straight in home.ts it works (see below).

export class HomePage {
  products;

  ngOnInit(){

      this.storage.get('products') // returns a promise which returns data or error
        .then(
          (products) => {
                          products? this.products = products : this.products = [];          
        })  
        .catch(
          err => console.log(err)
        );                     
  }
}

I would like to have the code in ProductService. And I don't know why its working this way.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

fetchProducts is asynchronous, you should use the results inside a success callback that this function could take as parameter:

fetchProducts(success: (products: any[]) => void): void {
    this.storage
        .get("products")
        .then(products => callback(products || []))
        .catch(err => console.log(err));
}

and then:

ngOnInit() {
    this.productService.fetchProducts(products => this.products = products);
}

Other possibilities include to make fetchProducts return a Promise or Observable so that you can subscribe to it in your ngInit method.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda