Angular RxJS Observable Class
Angular RxJS Observable Class
Objective: In this article, you will use the HTTP library in Angular in conjunction with RxJS, HTTP GET request, and RxJS Observables to handle an asynchronous web API request.
Pre-requisite Before completing this article, you should have already installed all pre-requisite tooling including. Visual Studio Code, Node Package Manager (NPM), Node, Angular CLI.
Setup✨
On your local machine, open Visual Studio Code.
Go to the File menu and select the Open Folder option.
Create a new project for this exercise and select this folder.
Create a new project: open terminal by Ctrl + backtick(`) key then run ng new angular-medium command
Bootstrapping Your Environment✌
In Visual Studio Code, Ctrl + backtick(`) key press and select the Open in Terminal option.
Run the angular-medium project using npm:
npm start
To start the port correctly in your desired port use:
npm start --port 8000 --open
Add the Http Module
Within the app folder, open the app.module.ts file.
Add an import statement to the top of your file that imports the HttpClientModule module from the @angular/common/HTTP package:
import {HttpClientModule} from '@angular/common/http';
3. Update the NgModule decorator by adding the HttpClientModule module to the values in the import array property of the NgModule decorator:
@NgModule({
imports: [
BrowserModule,
HttpClientModule
],
declarations: [
AppComponent
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Invoke HTTP Get Method
Within the app folder, open the app.component.ts file.
Add a new import statement to import the HttpClient from the @angular/common/http library module:
import { HttpClient } from '@angular/common/HTTP;
3. Add a new import statement to import the Observable member (class) from the rxjs library module:
import {Observable} from 'rxjs';
4. Within the AppComponent class, add a new property named dataItems of type string:
`export class AppComponent {` dataItems2:ItemList\[\]=\[\];
`}`
5. Within the AppComponent class, add a new empty constructor:
`export class AppComponent {` dataItems2:ItemList\[\]=\[\]; `constructor() {
}
}`
6. Add a model named ItemList. And import into the app.component.ts file
import { ItemList } from './model';
export class ItemList{
public userId: number;
public id: number;
public title: string
}
7. Update the constructor by adding a parameter of type httpclient:
constructor(private httpclient : HttpClient) {
}
8. Within the AppComponent class, add a new method named getDummyApiData2:
`export class AppComponent {` dataItems2:ItemList\[\]=\[\]; `constructor(private httpclient : HttpClient) { ... }
private` getDummyApiData2`() {
}
}`
9. Update the getDummyApiData2 method signature by adding the return type of Observable:
`private` getDummyApiData2`() : Observable<ItemList[]> {
}`
10. Within the getDummyApiData2 method, return the result of invoking the get method on the httpclient private variable:
`private getbiponIPAddress() : Observable<ItemList[]> {
return` this.httpclient.get<ItemList\[\]>('https://jsonplaceholder.typicode.com/posts')`;
}`
11. Returning to the empty constructor, add a line of code to invoke the getDummyApiData2 method:
`constructor(private httpclient : HttpClient) {
this.`getDummyApiData2`()
}`
12. Subscribe to the data being available by invoking the subscribe method:
`constructor(private httpclient : HttpClient) {` this.getDummyApiData2()
.subscribe(res => {
this.dataItems2 = res;
});`
}`
13. Update the subscribe method by adding an inline anonymous function to get the result of the IP Address request and save it to the dataItems2 property in the AppComponent class:
`constructor(private httpclient : HttpClient) {` this.getDummyApiData2()
.subscribe(res => {
this.dataItems2 = res;
});`
}`
14. Your final app.component.ts class should now look like this:👀
import {Component} from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {Observable} from 'rxjs';
@Component({
selector: 'app',
templateUrl: './app.component.html',
styleUrls: './app.component.css',
})
export class AppComponent {
dataItems2:ItemList[]=[];
constructor(private httpclient : HttpClient) {
this.getDummyApiData2()
.subscribe(res => {
this.dataItems2 = res;
});
}
private getDummyApiData2() : Observable<ItemList[]> {
return this.httpclient.get<ItemList[]>('https://jsonplaceholder.typicode.com/posts');
}
}
###Another way 🎁
Just restructure for a smarter way to data access.
app.component.ts
import { SampleService } from './sample.service';
dataItems:ItemList[]=[];
constructor(
private sampleService:SampleService,
private httpclient: HttpClient) {
this.getDummyApiData();
}
private getDummyApiData(){
this.sampleService.getDataList().subscribe(data=>{
this.dataItems=data;
})
sample.service.ts file
getDataList():Observable<ItemList[]>{
return this.http.get<ItemList[]('https://jsonplaceholder.typicode.com/posts');
}
app.component.html file
- {{item.title}}
Render HTTP Response👏
Within the app folder, open the app.component.html file.
Render the value of the dataItems2 property iterate by adding *ngFor directive and a template expression:
`<h1>Dummy App</h1>
<strong>` **Example List Item:**`:</strong>
`<ul>
<li \*ngFor="let item of dataItems2">
{{item.title}}
</li>
</ul>
Output
Reference