Reputation: 372
in angular 1.x services were injected by specifying its registered name. For example using TypeScript:
// appointments.ts
export interface IAppointmentServices {
retrieve(start: Date, end: Date): Appointment[]
}
// appointment-services.ts:
class AppointmentServices implements IAppointmentServices {
retrieve(start: Date, end: Date): Appointment[] {
...
}
}
angular.module('appointments')
.service('AppointmentServices', AppointmentServices);
// appointment-controller.ts
class AppointmentController {
constructor (private service: IAppointmentService) {
}
// pay attention that 'AppointmentServices' is the registered name
// not a hard reference to the class AppointmentServices
static $inject = ['AppointmentServices']
}
pay attention that the controller implementation has no reference in any way to the file nor the class that implements the service
but in angular 2, to accomplish a similar DI you have to something as in these lines:
import {Component} from 'angular2/core';
import {AppointmentServices} from 'appointment-services';
@Component({
...
providers: [AppointmentServices]
})
export class Appointment {
constructor (service: AppointmentServices) {
...
}
}
pay attention that in the second import above, I have to specify the location where the AppointmentServices is implemented as well as the name of the class which represent a glue between the component and the implementation of the service
Is there a way in angular2 to inject the service without specifying the class and the file that implements it?
I think this angular2 approach is kind of a step back in terms of IoC accomplished in its predecessor if DI has to be done in such a way!
Upvotes: 0
Views: 74
Reputation: 67131
There is no such way, because this is simply how import / export
functionality works. In order to import
something, it must be equally exported
(by the same name), somewhere else.
Hence why in one file (appointment-services) you have
export class AppointmentServices
And the other component file you use Object Destruction to "grab" that specific thing (which was exported from it)
import { AppointmentServices } from 'appointment-services';
These two are linked, in that, that is how they access each other. Although this may seem "backwards", TypeScript and IDEs now have the power to refactor an entire library with ease now, since they are aware of these export/imports.
So if you wanted to change it to export class AnotherAppoinmentService
instead, you could refactor it, and your IDE could automatically switch them all for you!
Note: Angular1 modules stored everything as "String", why things were loosely specified. You typically had to do MyClass.name for example
Upvotes: 2