Understanding REST API in Angular

Implementing a REST API in Angular involves a few steps.

Importing the HttpClientModule

Angular comes with a built-in module called HttpClientModule that allows you to make HTTP requests to a REST API. To use it, you need to import it into your Angular project. Open the app.module.ts file and add the following code.

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    HttpClientModule
  ],
  // other module configurations
})
export class AppModule { }

Creating a Service

In Angular, services are used to encapsulate data and functionality that can be shared across components. Create a service to handle API calls. For example, create a service called UserService.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class UserService {
  private apiUrl = 'https://my-api.com/users';

  constructor(private http: HttpClient) { }

  getUsers() {
    return this.http.get(this.apiUrl);
  }

  getUserById(id: number) {
    return this.http.get(`${this.apiUrl}/${id}`);
  }

  addUser(user: any) {
    return this.http.post(this.apiUrl, user);
  }

  updateUser(id: number, user: any) {
    return this.http.put(`${this.apiUrl}/${id}`, user);
  }

  deleteUser(id: number) {
    return this.http.delete(`${this.apiUrl}/${id}`);
  }
}

In this example, the UserService has methods to make all the CRUD operations to a REST API. Each method uses the HttpClient service to make the actual HTTP requests.

Using the Service in a Component

Now that you have a service to handle API calls, you can use it in a component. For example, create a component called UserListComponent.

import { Component, OnInit } from '@angular/core';
import { UserService } from '../user.service';

@Component({
  selector: 'app-user-list',
  template: `
    <h2>User List</h2>
    <ul>
      <li *ngFor="let user of users">{{ user.name }}</li>
    </ul>
  `
})
export class UserListComponent implements OnInit {
  users: any[] = [];

  constructor(private userService: UserService) { }

  ngOnInit() {
    this.userService.getUsers().subscribe((data: any[]) => {
      this.users = data;
    });
  }
}

In this example, the UserListComponent uses the UserService to get the list of users from the API and displays it in the template.

Handling Errors

It’s important to handle errors when making API calls. You can do this by using the catchError operator of RxJS. For example, modify the getUserById method of the UserService to handle errors.

import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';

getUserById(id: number) {
  return this.http.get(`${this.apiUrl}/${id}`).pipe(
    catchError((error: any) => {
      console.error(error);
      return throwError('An error occurred');
    })
  );
}

In this example, the getUserById method uses the catchError operator to log the error and return an error message.

That’s it! With these steps, you can implement a REST API in Angular.


Similar Articles