AngularJS 2 is an open source, MV* Javascript framework developed by Google. It is widely use across the industry to build web applications. In this article, we will demonstrate the use of Http Get in Angular 2.
Introduction
AngularJS 2 is an open source, MV* JavaScript framework developed by Google. It is widely use across the industry to build web applications. In this article, we will demonstrate the use of Http Get in Angular 2.
Using the code
Open app.ts file inside the src folder and write the below code
//our root app component
import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {
HttpModule
Http,
Response
} from '@angular/http';
import { Observable } from 'rxjs';
// Annotation section
@Component({
selector: 'my-app',
template: `
<div style="width: 50%; margin: 0 auto;">
<user-selector></user-selector>
</div>
`,
})
// Component controller
export class App {
constructor() { }
}
// Annotation section
@Component({
selector: 'user-selector',
templateUrl: 'user-information-apps.html'
})
// Component controller
export class UserInformation {
users:Observable<Array<any>>
url: string;
constructor(private _http: Http) {
this.url='http://jsonplaceholder.typicode.com/posts';
} //end constructor
getUserDetails(){
this._http.get(this.url)
.subscribe((res: Response) => {
this.users = res.json();
});
} //end getUserDetails
}
}
@NgModule({
imports: [
BrowserModule,
HttpModule
],
declarations: [ App,UserInformation ],
bootstrap: [ App ]
})
export class AppModule {}
Angular 2 follows modular structure.The Angular apps contains many modules each one of which is dedicated for a single purpose.
In Angular 1.x, we can define a service via 5 different ways viz.
- Factory
- Service
- Provider
- Constant
- Values
But in Angular 2 the only way to define a service is through class.
The Angular 2 http module resides in a separate java script file from Angular 2 core and it depends on the RxJS library. We can open the config.js file to find references to both modules (code removed for brevity)
//map tells the System loader where to look for things
map: {
'app': './src',
....................................................
.....................................................
'@angular/http': 'npm:@angular/http/bundles/http.umd.js',
'@angular/http/testing': 'npm:@angular/http/bundles/http-testing.umd.js',
'rxjs': 'npm:rxjs',
....................................................
.....................................................
},
//packages defines our app package
packages: {
app: {
main: './main.ts',
defaultExtension: 'ts'
},
rxjs: {
defaultExtension: 'js'
}
}
In order to enable Http in the application, we need to import the below modules from the @angular/http module
import {
HttpModule
Http,
Response
} from '@angular/http';
and the below from rxjs
import { Observable } from 'rxjs';
RxJs stands for Reactive Extensions for JavaScript. It's an implementation of Observables for JavaScript. For more information, please read this article.
Http : It is the Angular 2 http service that provides the API to make HTTP requests with methods corresponding to HTTP verbs like get, post, put, delete.
Response : It follows the Fetch API Specification and represents a response from an HTTP service.
Observable : It is the async pattern used in Angular 2. It notifies the subscribers/observers when some changes happens. It follows the observer design pattern.
The imports property of @NgModule will be like
@NgModule({
imports: [
BrowserModule,
HttpModule //<-- HttpModule imported
],
declarations: [ App,UserInformation ],
bootstrap: [ App ]
})
In the constructor of the UserInformation class, we have injected HTTP Dependency Injection.
constructor(private _http: Http) {
this.url='http://jsonplaceholder.typicode.com/posts';
} //end constructor
Next we have invoked the service from getUserDetails() method
getUserDetails(){
this._http.get(this.url)
.subscribe((res: Response) => {
this.users = res.json();
});
} //end getUserDetails
}
Angular 1.x uses Promises to load data asynchronously while Angular 2 uses a similar pattern called Observables. The Observable classes in Angular 2 are provided by the ReactiveX library.
In Angular 1.x, $http is use for Http service processing while Agular 2 uses Http Service whose http.get() method returns an Observable object. The subscribe() method observes the output return by http.get() method. For parsing the response as JSON, we use res.json().
Now we need to bind the data to the view. So let's create the below user-information-apps.html
<h1>
<b>
<font color="blue"> User Information</font>
</b>
</h1>
<table border="1">
<tr>
<th style="background-color: #4CAF50;">Id</th>
<th style="background-color: #4CAF50;">User Id</th>
<th style="background-color: #4CAF50;">Title</th>
<th style="background-color: #4CAF50;">Body</th>
</tr>
<tr *ngFor="let u of users">
<td><span>{{u.id}}</span></td>
<td><span>{{u.userId}}</span></td>
<td><span>{{u.title}}</span></td>
<td><span>{{u.body}}</span></td>
</tr>
</table>
<div>
<button (click)="getUserDetails()" id="btnUserDetails">Invoke User Details Service</button>
</div>
The let keyword of Type Script (and ES6) allows to define variables with true block scope. ngFor of Angular 2 is the replacement for ng-repeat of AngularJS 1.x. This directive instantiates a template once per item from an iterable. The *is a shorthand for using the new Angular 2 template syntax with the template tag. It is the syntactic sugar that brings the structural Directive of Angular 2.
Now open the index.html in Fire Fox and the result(partial)
References
ANGULAR 2 HTTP EXAMPLE
Conclusion
This article covers the basic concepts of Observable, Http Service, Dependency Injection of Angular 2 with an example. Hope this will be helpful. Thanks for reading. Zipped file is attached herewith.