Posts

Showing posts with the label angular 2

Angular (2+): What does the @Injectable() decorator do?

Image
If you've looked at the description in your editor for the @Injectable() decorator, you'll see something like this: Look at that interface.. It's blank! 😕 So why do we need it? The Angular documentation says this: At runtime, injectors can read class metadata in the transpiled JavaScript code and use the constructor parameter type information to determine what things to inject. Not every JavaScript class has metadata. The TypeScript compiler discards metadata by default. If the  emitDecoratorMetadata  compiler option is true (as it should be in the  tsconfig.json ), the compiler adds the metadata to the generated JavaScript for  every class with at least one decorator . While any decorator will trigger this effect, mark the service class with the  @Injectable()  decorator to make the intent clear. Read the last sentence again: "...any decorator will [work]...". You can actually make your own decorator and use that instead of the @Inject...

Angular (2+): Core vs Shared Modules

Angular: Core vs Shared Modules If you're new to Angular, you might get confused between these two commonly used modules. So what do you put in either components?  What goes in CoreModule? Your CoreModule contains code that will be used to instantiate your app and load some core functionality.  The clearest and most important use of the CoreModule is the place to put your global/HTTP services. The idea is to make sure only one instance of those services will be created across the entire app. The CoreModule, by convention, is only included in your entire app once in AppModule (only in the "import" property of the "@NgModule()" decorator inside your main app.module.ts, not in any other module's "import") and this will ensure services inside it will be only created once in the entire app. This is especially important if you intend to lazy-load your feature modules. Since lazy-loaded modules are loaded on demand (eg when you access the rou...