Angular 18 RxJS Observable with Httpclient Example

By Hardik Savani July 2, 2024 Category : Angular

Hi Dev, I will show you how to create a service using RxJS Observable in angular 18 application step by step.

If you're unsure about using observable with HttpClient requests in an Angular application, I can guide you through it. We like using observables for HTTP requests because they help handle service requests and keep an eye on server responses. Observables are made available by rxjs.

Now, I'll provide a straightforward example of an HTTP request with observables in Angular. We'll use the JSON Placeholder API to make our API requests. Follow these steps to see the example, and I've included a preview at the bottom for you to check out.

Step for Creating Http Client Request Service in Angular 18

  • Step 1: Create Angular 18 Project
  • Step 2: export provideHttpClient()
  • Step 3: Create Post Class
  • Step 4: Create Service for API
  • Step 5: Use Service to Component
  • Step 6: Updated View File
  • Run Angular App

So, let's see the below example step on step how to create an RxJS Observable service and how to use it.

Step 1: Create Angular 18 Project

You can easily create your angular app using below command:

ng new my-new-app

Step 2: export provideHttpClient()

In this step, we need to export provideHttpClient() to app.config.ts file. so let's import it as like bellow:

src/app/app.config.ts

import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
  
import { routes } from './app.routes';
import { provideAnimations } from '@angular/platform-browser/animations';
  
import { provideHttpClient } from '@angular/common/http';
   
export const appConfig: ApplicationConfig = {
  providers: [provideRouter(routes), provideAnimations(), provideHttpClient()]
};

Step 3: Create Post Class

In this step, we will simply create a Post class and define data types of returning data. so let's create a post.ts file and put the bellow code:

src/app/post.ts

export class Post {
    constructor(
      public body: string,
      public id: number,
      public title: string,
      public userId: number
    ) {}
}

Step 4: Create Service for API

Here, we need to create service for http client request. we will create service file and write client http request code. this service will use in our component file. So let's create service and put bellow code:

ng g s post

Now let's add code as like bellow:

src/app/post.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Post } from './post';
    
@Injectable({
  providedIn: 'root'
})
export class PostService {
      
  private url: string = 'https://jsonplaceholder.typicode.com/posts';
  constructor(private httpClient: HttpClient) { }
    
  public getPosts(): Observable{
    return this.httpClient.get(this.url);
  }
    
}

Step 5: Use Service to Component

Now we have to use this services to our app component. So let's updated code as like bellow:

src/app/app.component.ts

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';
  
import { PostService } from './post.service';
import { Post } from './post';
  
@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule, RouterOutlet],
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  
  posts = new Array<Post>();
      
  constructor(private service:PostService) {}
      
  ngOnInit() {
      this.service.getPosts().subscribe(response => {
          this.posts = response.map(item => 
            {
              return new Post( 
                  item.body,
                  item.id,
                  item.title,
                  item.userId
              );
            });
        });
  }
    
}

Step 6: Updated View File

Now here, we will updated our html file. let's put bellow code:

src/app/app.component.html

<div class="container">
  <h1>Angular 18 Observables HttpClient Example - ItSolutionStuff.com</h1>
    
  <table class="table table-bordered">
    <tr>
      <th>ID</th>
      <th>Body</th>
      <th>Title</th>
      <th>UserID</th>
    </tr>
    <tr *ngFor="let post of posts">
      <td>{{ post.id }}</td>
      <td>{{ post.body }}</td>
      <td>{{ post.title }}</td>
      <td>{{ post.userId }}</td>
    </tr>
  </table>
</div>

Run Angular App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Angular app:

ng serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:4200

you will see the layout below:

I hope it can help you...

Shares