I am currently learning the Angular framework (version 5) after developing 2 years with the AngularJS 1.x framework, so I ask myself a lot of questions and one of them is the way to properly import a service provided by another module that the one of my application.
Let's say that I have a CoreModule
for example which provide a MyService
service, and let's say that the project has the following file tree:
app/
app.module.ts
...
pages/
clients/
clients.component.html
clients.component.css
clients.component.ts
...
core/
core.module.ts
providers/
my-service.service.ts
Now let's say that my clients
page needs to inject the MyService
service from the CoreModule
module. To do that I will put MyService
in the providers list of the CoreModule
module. And I will import the CoreModule
in my AppModule
.
If I well understood, by doing such an import, I will say to my application to use the MyService
service when it is required in the .ts files of the AppModule
module.
But the thing I cannot understand is the inclusion of the .ts file declaring the service in my application code. Indeed, if I want to use the MyService
service, I will do something like that in my Clients
class:
constructor(private service: MyService) {
// using of the injected service
}
But TypeScript needs the reference of the .ts file which declared the service. My first try would be to import the file by following the file tree:
import { MyService } from '../../core/providers/my-service.service';
But it does not feel right to me because when I import an Angular service I do not have to specify the path to access to the file which declare the service in question. Example with the HttpClient
service:
import { HttpClient } from '@angular/common/http';
Actually, I would like to be able to import my core service in my application page by referencing the module and not by passing the path of the .ts file.
At that point, I don't know if it is even possible or if I misunderstood the use of service from other modules.