Creating services with the provider

Sometimes, it might be interesting to create configurable services. They are called providers, and despite being more complex to create, they can be configured before being available to be injected inside other components. While the factory works by returning an object and the service with the constructor function, the provider relies on the $get function to expose its behavior. This way, everything returned by this function becomes available through the dependency injection. In the following code, we refactored our service to be implemented by a provider. Inside the $get function, the calculateTicket method is being returned and will be accessible externally.
services.js
snippet
parking.provider("parkingService", function(parkingConfig) {
    var _parkingRate = parkingConfig.parkingRate;
    var _calculateTicket = function(car) {
        var departHour = new Date().getHours();
        var entranceHour = car.entrance.getHours();
        var parkingPeriod = departHour– entranceHour;
        var parkingPrice = parkingPeriod * _parkingRate;
        return {
            period: parkingPeriod,
            price: parkingPrice
        };
    };
    this.setParkingRate = function(rate) {
        _parkingRate = rate;
    };
    this.$get = function() {
        return {
            calculateTicket: _calculateTicket
        };
    };
});
In order to configure our provider, we need to use the config function of the Module API, injecting the service through its function. In the following code, we are calling the setParkingRate method of the provider, overwriting the default rate that comes from the parkingConfig method.
config.js
parking.config(function (parkingServiceProvider) {
	parkingServiceProvider.setParkingRate(10);
});
The other service components such as constants, values, factories, and services are implemented on the top of the provider component, offering developers a simpler way of interaction.
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +