mp3por
mp3por

Reputation: 1852

Angular2 module system with TS

I was looking at this : https://github.com/mgechev/angular-seed in order to understand the Angular Module System in its most basic form.

In this seed project there is a SharedModule which has both index.ts and shared.module.ts. In shared.module.ts it does the exports the Angular way - with directives, exports, providers and etc. In index.ts it reexports them. In app.module.ts it imports SharedModule.forRoot() which is perfect - this registeres the NameListService to be available to the whole application. However when the NameListService is to be used it has to be imported and this is done via import { NameListService } from '../shared/index'; as presented in home.component.ts which by the way is part of the home.module.ts which also imports the SharedModule.

According to me this is totally wrong.

Why would I have to import it like this - this breaks modularity - what if I am using a module which I have not written and thus do not know where exactly to look for a file ?

Why would I then bother with creating and registering things in shared.module.ts if then I will have to use them via the shared/index.ts instead of just using the shared/index.ts ?

Best regards

Upvotes: 0

Views: 197

Answers (1)

George Allen
George Allen

Reputation: 21

I believe this question has been answer over on Angular's website: https://angular.io/docs/ts/latest/cookbook/ngmodule-faq.html#!#q-ng-vs-js-modules

I would recommend reading https://angular.io/docs/ts/latest/guide/ngmodule.html for an in depth guide on ngModules

Update

Try and think of it in terms of the two different compilers: the angular compiler and the typescript compiler.

The fact you reference the UserService by path allows the typescript compiler to find it. If it couldn't find the UserService, your code would not compile. It also provides you with intellisense and type checking. The angular compiler doesn't care about this.

Adding the UserService to ngModule allows the Angular compiler to create an instance of it and provide it to your components, services etc. If you did not do this you would get an error saying something like: "no provider found for UserService"

Upvotes: 2

Related Questions