Help with providers


#1

Hi,

I’m trying to get started with a creating a simple provider. What I’m currently struggling is to use multiple functions in my provider.

I created a provider named price with the following command: ionic generate provider.
Inside my provider, I created a function named getPrice, but instead of just returning a value, it asks another function, which pulls the value from native storage. So inside my page.ts, I have this:

getPrice(currency)
{
this.myProvider.getPrice(currency).then((price) => {
this.price = price;
});
}

and my provider, looks like this:

getPrice(currency)
{
return new Promise((price, reject) => {
anotherFunction(currency);
});
}

anotherFunction(currency)
{
this.nativestorage.getItem('price').then(
data => {
this.price = data;
});
}

So as you can see, anotherFunction has the price, which needs to be returned to my page. How can I make the first function in my provider (getPrice) to return anotherFunction’s data?

Hope it was clear enough. Quite late in the day here.

Thanks ahead for any help :slight_smile:


#2

Going the way you have it set-up you’d need to do something like this:

getPrice(currency)
{
  return anotherFunction(currency).then(_ => this.price);
}

anotherFunction(currency)
{
  return this.nativestorage.getItem('price').then(data => this.price = data);
}

I’m not entirely sure why you have two functions that effectively seem to be doing the same thing, but I’m also unsure of the larger context.

If you’re trying to load the data and then store it (as you clearly are doing here), you could always re-work your provider to just load once. Otherwise I’m not sure there’s much reason to load and store the result every time. I could just not be thinking of a proper use case though.


#3

Hi,

Well the code is a bit more complex, these were examples.

I have a related question, can I update the page from the provider?

Let’s say I have a page with <h1>{{title}}</h1> and in page.ts, I call my provider. How can I change the title from within the provider?