Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

212
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!