在ANGULAR的SERVICE中,哪种才是最基本的实现?(Provider)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在ANGULAR的SERVICE中,哪种才是最基本的实现?(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。
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 }; }; });
以上是关于在ANGULAR的SERVICE中,哪种才是最基本的实现?(Provider)的主要内容,如果未能解决你的问题,请参考以下文章