Quantcast
Channel: Ionic Forum - Latest topics
Viewing all articles
Browse latest Browse all 70440

Ionic Storage as promise with providing initial data

$
0
0

@coffeeee wrote:

Hello,

so I would like to achieve the following within my Ionic Storage provider (Ionic v. 3):

  • on app open, check if storage is available
  • if it is not available, create storage with http request, if http request not possible (return null), then populate with new data on the fly
  • if available, simply use existing one.

This is my solution (provider):

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';

@Injectable()
export class MovieProvider {

  movieCollection: any;

  private initData() {
    this.buildMovieItemsViaHttp().then(data => this.movieCollection = data);
    if (this.movieCollection != null)
    {
      this.storage.set('storageMovieCollection', this.movieCollection);
    } else {
      //this.storage.set('storageMovieCollection', bla...load some generated data on the fly);
    }
  }

  private buildMovieItemsViaHttp(){
    return new Promise(resolve => {
        this.http.get('assets/data/movieCollection.json') //will be replaced with actual server data
          .subscribe(res => {
            resolve(res);
            console.log(res)
          });
    });
  }

  getMovieItems() {
    this.storage.get('storageMovieCollection').then((data) => {
      return data;
    });
  }

  constructor(private http: HttpClient, private storage: Storage) {
    this.storage.get('storageMovieCollection').then((data) => {
      if(data != null)
      {
        this.initData();
      }
      else
      {
        //just use existing one...
      }
    });
  }

The console.log will return all the items. So this is working.

However, doing the following inside my init will always return undefined:
this.buildMovieItemsViaHttp().then(data => this.movieCollection = data);

Apparently it is not able to fetch the data from the promise. I fear I am using this wrong.

Thanks in advance for your ideas and suggestions!

Posts: 1

Participants: 1

Read full topic


Viewing all articles
Browse latest Browse all 70440

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>