Categories

Monday, December 23, 2024
#919814419350 therichposts@gmail.com
Angular 14Bootstrap 5

How to use Angular RXJS Observable to store API Data?

How to use Angular RXJS Observable to store API Data?

Hello guys how are you? Welcome back to my blog therichpost.com. Today in this post I will let you know How to use Angular RXJS Observable to store API Data?

Guys in this working demo I will store api data inside RXJS Observal in Angular 14 application.

RxJS (Reactive Extensions for JavaScript) and Observables are a collection of values that we use to contain data retrieved asynchronously.

Working Live Demo

Friends now I proceed onwards and here is the working code snippet and please use carefully this to avoid the mistakes:

1. Firstly friends we need fresh angular 14 setup and for this we need to run below commands but if you already have angular 14 setup then you can avoid below commands. Secondly we should also have latest node version installed on our system:

npm install -g @angular/cli 

ng new angulardemo //Create new Angular Project

cd angulardemo // Go inside the Angular Project Folder

2. Now friends, here we need to run below commands into our project terminal to install bootstrap 5 modules and create service file into our angular application:

npm install bootstrap

npm i @popperjs/core

ng g service apidata

3. Now friends, here we need to add below  into our angular.json file:

"styles": [
              ...
              "node_modules/bootstrap/dist/css/bootstrap.min.css"
          ],
"scripts": [
              ...
               "node_modules/bootstrap/dist/js/bootstrap.min.js"
           ]

4. Now friends we just need to add below code into src/app/apidata.service.ts file:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { User } from './users';
import { Observable } from 'rxjs'; //RxJS (Reactive Extensions for JavaScript)
//Observables are a collection of values over time that we use to contain data retrieved asynchronously. 

import { catchError, retry } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class ApiServicesService {
  apiUrl:string = "https://therichpost.com/testjsonapi/users/";
  constructor(private http: HttpClient) { }

  //Notice that, here the data type for Observable is User list and the return type of get method is getUsers. User is an interface. 
  getUsers(): Observable<User[]>  {
    // now returns an Observable of Config
    return this.http.get<User[]>(this.apiUrl);
  }
}

5. Now friends we just need to create new file users.ts into src/app/ folder and below code inside that:

//Interface is a specification that identifies a related set of properties and methods to be implemented by a class.
export interface User {
    id: number;
    name: string;
    email: string;
    job_title: string
  }

6. Now friends we just need to add below code into src/app/app.module.ts file:

...
import { HttpClientModule } from '@angular/common/http';
@NgModule({
  
  imports: [
    ...
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

7. Now friends we just need to add below code into src/app/app.component.ts file:

import { Component } from '@angular/core';
import { ApiServicesService } from './api-services.service';
import { User } from './users';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  users: User[] =[];
  constructor( apiService:ApiServicesService){
  
  apiService.getUsers()
  .subscribe(response => 
    {
      this.users = response;
    });
}
}

7. Now friends we just need to add below code into src/app/app.component.html file:

<table class="table">
        <thead>
          <tr>
            <th scope="col">ID</th>
            <th scope="col">Name</th>
            <th scope="col">Email</th>
            <th scope="col">Job Title</th>
          </tr>
        </thead>
        <tbody>
          <tr *ngFor="let user of users">
            <th scope="id">{{ user.id }}</th>
            <td>{{ user.name }}</td>
            <td>{{ user.email }}</td>
            <td>{{ user.job_title }}</td>
          </tr>
        </tbody>
      </table>

Friends in the end must run ng serve command into your terminal to run the angular 14 project.

Now we are done friends. If you have any kind of query, suggestion and new requirement then feel free to comment below.

Note: Friends, In this post, I just tell the basic setup and things, you can change the code according to your requirements.

I will appreciate that if you will tell your views for this post. Nothing matters if your views will be good or bad because with your views, I will make my next posts more good and helpful.

Jassa

Thanks

therichpost
the authortherichpost
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know WordPress, Core php, Angularjs, Angular 19, MedusaJs, Next.js, Bootstrap 5, Nodejs, Laravel, Codeigniter, Shopify, Squarespace, jQuery, Google Map Api, Vuejs, Reactjs, Big commerce etc.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.