Angular RxJS Observable Class
Tags: angular, rxjs, observables, typescript
Published: 2020-11-11 08:25:18

---
title: Angular RxJS Observable Class
published: true
description: Angular in conjunction with RxJS, HTTP GET request, RxJS Observables to handle an asynchronous web API request.
tags: angular, rxjs, Observables, typescript
//cover_image: ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/mkmiyr7bdug8u8yaxmcs.png)
---

**Objective**: In this article, you will use the HTTP library in Angular in conjunction with RxJS, HTTP GET request, RxJS Observables to handle an asynchronous web API request.

**Pre-requisite** Prior to completing this article, you should have already installed all pre-requisite tooling including: Visual Studio Code, Node Package Manager (NPM), Node, Angular CLI.

**Setup**✨

1. On your local machine, open **Visual Studio Code**.
2. Go to the **File** menu and select the **Open Folder** option.
3. Create a new project for this exercise and select this folder.
4. Create a new project: open terminal by **Ctrl + backtic(`)** key then run ng **new angular-medium** command

**Bootstrapping Your Environment**✌

1. In Visual Studio Code, **Ctrl + backtic(`)** key press and select the **Open in Terminal** option.
2. 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**

1. Within the app folder, open the app.module.ts file.
2. 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**

1. Within the app folder, open the **app.component.ts** file.
2. 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 **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 return type of **Observable<Response>**:

```
private getDummyApiData2() : Observable<ItemList[]> {
}
```

10.Within the **getDummyApiData2** method, return the result of invoking the **get** method on the **httpclient** private variable:

* https://jsonplaceholder.typicode.com/posts

```
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 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

```
<ul>
    <li *ngFor="let item of dataItems">
        {{item.title}}
    </li> 
</ul>
```

**Render HTTP Response**

1. Within the **app** folder, open the **app.component.html** file.
2. 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**

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/x4c2sxn0ltkvg6e2pk7x.png)

[Github](https://github.com/bipon68/angular-medium)
[StackBlitz](https://stackblitz.com/github/bipon68/angular-medium)


**Reference**

[Fake Online REST API for Testing and Prototyping](https://jsonplaceholder.typicode.com/)
[TypeScript](https://scrimba.com/learn/intrototypescript)
[Angular CLI](https://angular.io/cli)
[Right way to make API calls](https://medium.com/javascript-in-plain-english/the-right-way-to-make-api-calls-in-angular-5cc03a62bf43)