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.
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.