Using an API globally across an app

Hi there, apologies in advance for any misuse of terms of lack of knowledge, I’ve only been developing in Ionic for 2 months!

I’m developing an app which requires the parsing of JSON responses from a live API endpoint, which I have so far successfully implemented. However, I want this API response data available to import globally across each of my app’s pages, so I don’t have to implement the code over and over.

My impression from my development and research so far in Ionic is that I may want what’s known as a “provider”, or possibly “service”? I’m unsure if these are one and the same or totally different. My boss however, thinks I want this implemented using a JSON config file, which may or may not be in a format such as .xml or .yml.

To be honest, I really don’t mind what format this takes, so long as it works! I’ve tried to mimic what’s seen in the conference demo app, but got a bit lost in trying to implement something myself. If anyone could provide some pointers, particularly docs or examples of such an API “service” I would appreciate it. :slight_smile:

I’m only about 3 months in to Ionic, so I’m no pro, and won’t go into detail. But, I was terribly confused by this concept at first too. To literally create a provider, run ionic generate provider MyProvider Replace MyProvider with whatever you want. Now you have a provider. It’s not something that you install, not a plugin or anything. To import that provider into your seperate pages, add import { MyProvider } from '../providers/my-provider'; Or whatever path gets you to your provider folder. Do the same in your app.module.ts file, then add MyProvider (or your name for YourProvider) to the section called providers: [ ] also in app.module.ts.
It’ll look like this:


Edit: When you ```import {  MyProvider } from '../providers/myProvider';``` in to one of your pages, declare it in the constructor too. So:
```constructor(public myProvided: MyProvider) {
 } ```
After those steps are done, you can link to API's, databases, etc... and pass data around with that provider. Someone else will have to take over at this point. But that's a pretty clear cut start.
1 Like

Thanks for the reply! I’ll have a go with this and see how I get on. :slight_smile:

Good Luck!. If you’ve got any questions let me know. I can help as far as my knowldege allows. Hope it works our for you

1 Like