Difference between a regular service and a provider?

Hi everyone, could someone explain what is the difference between using a provider over a regular service? For example,

I have a service (I created this in app/services/)

import {Http} from '@angular/http';
import 'rxjs/Rx';

@Injectable()
export class CasesService {
    http: any;
    baseUrl: String;
    apiKey: String;

    constructor(http:Http) {
        this.http = http;
        this.baseUrl = 'http://localhost:8100/api';
        this.apiKey = 'xxx';
    }

    getCases(token, page) {
        return this.http.get(this.baseUrl + '/?key=' + this.apiKey +  '&token=' + token + '&page=' + page + '&per_page=20')
            .map(res => res.json());
    }

    getCaseByRef(token, caseRef) {
        return this.http.get(this.baseUrl + '/case/' + caseRef + '?key=' + this.apiKey + '&token=' + token)
            .map(res => res.json());
    }
}

This is then imported into any page that requires it and added to the constructor. It works fine. But I see examples using providers which look almost identical but the provider is added to the providers array in app.module.ts, what’s the difference?

1 Like

Ah I think I’ve found the answer - leaving it here in case it help anyone else.

If you add it to the bootstrap then a single instance of the service will be created that all components in the application will share – making it a great way to share data between components. If you add the provider to an individual component, then a new instance will be created for just that one component.

Taken from An In-Depth Explanation of Providers in Ionic 2 | Josh Morony

6 Likes

That is how it used to work but it’s different now. A provider/service are the same thing, if you want to use dependency injection (injecting things through the constructor) you need to add the @Injectable decorator and add it to the providers array. If you are just creating a simple class that you just want to create new instances of then you don’t need to add it as a provider (you would just instantiate a new instance of it, i.e. let myThing = new Thing();

6 Likes

Hey, thanks for the reply - great blogs by the way, very helpful!

So, am I right in thinking if I want one instance of a service then I should create it as a provider? For example, something responsible for storage?

Thanks again

Yes, wherever you inject a provider throughout the application it will reference a single instance.

1 Like

The terminology (provider vs. service) is irrelevant. What matters is where you declare it in a providers stanza. 99% of the time you want app-wide singletons, so this should be done in the app module. I frequently see posts here where services are declared in the providers stanza of a particular page. That will give you a separate instance per page, which is rarely what is wanted.

2 Likes