AngularJS Essentials
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
Chapter 4<br />
Creating services with the provider<br />
Sometimes, it might be interesting to create configurable services. They are called<br />
providers, and despite being more complex to create, they can be configured before<br />
being available to be injected inside other components.<br />
While the factory works by returning an object and the service with the<br />
constructor function, the provider relies on the $get function to expose its<br />
behavior. This way, everything returned by this function becomes available<br />
through the dependency injection.<br />
In the following code, we refactored our service to be implemented by a provider.<br />
Inside the $get function, the calculateTicket method is being returned and will be<br />
accessible externally.<br />
services.js<br />
parking.provider("parkingService", function (parkingConfig) {<br />
var _parkingRate = parkingConfig.parkingRate;<br />
var _calculateTicket = function (car) {<br />
var departHour = new Date().getHours();<br />
var entranceHour = car.entrance.getHours();<br />
var parkingPeriod = departHour – entranceHour;<br />
var parkingPrice = parkingPeriod * _parkingRate;<br />
return {<br />
period: parkingPeriod,<br />
price: parkingPrice<br />
};<br />
};<br />
this.setParkingRate = function (rate) {<br />
_parkingRate = rate;<br />
};<br />
this.$get = function () {<br />
return {<br />
calculateTicket: _calculateTicket<br />
};<br />
};<br />
});<br />
[ 75 ]<br />
www.it-ebooks.info