今天刚好看到这一节。
节选一下,稍后,实操完成之后,会补上所有代码
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 }; }; });
时间: 2024-10-12 16:57:55