Share
Looking for Part One, click here.
In this blog article we will learn installing Angular Modules, Dependency Injections, Services, and Angular Lifecycle Hooks.
Locating and Installing Angular Modules
Angular has many modules for you to use in your application. It’s up to you as the developer to decide what you need.
The best way to find modules provided by Angular is by reading through the documentation’s API reference and filtering on the word module.
https://angular.io/api?query=module
The GET and POST request methods are part of the HttpModule in Angular.
In the root of your project type:
npm install @angular/http --save
This is an exact version number that we need.
npm install @angular/http@2.4.2 --save --save-exact
Then import HttpModule to vendor.ts and add it to app.module.ts
Dependency Injection
Dependency Injection is not a new concepts. A lot of frameworks take advantage of this common design pattern. Dependency Injection is like a factory kindly creating services where we need them. In an Angular application dependency injection creates a singleton of a given service. This comes in handy when you have multiple areas of your application that need to communicate with one another.
Import Http into one of your components
import { Http } from '@angular/http';
Pass the http: Http variable in your constructor function.
export class ComponentName {
constructor(http: Http) {
http.get( '/app/entries' ).toPromise().then( response => { debugger; }, error => { debugger; } );
}
}
Creating a Service
Services provide a way for separating business logic from components.
When you developing large applications you may need to represent the same data in a variety of ways across your application.
Placing business logic in services, helps your application stay DRY (Do Not Repeat Yourself)
Adding the service to the providers array in app.module.ts lets Angular know about the service when the app is compiled.
Angular then makes the service available to use in components through dependency injection.
Providers are not components but they are classes decorated with the injectable decorator.
Angular Lifecycle Hooks
- ngOnInit – gets called when component gets intialized
- ngOnDestroy – gets called when component gets destroyed
https://angular.io/guide/lifecycle-hooks
Sorry for the short aritcle, will be writing more soon…