Create Angular Service Using HttpClient

In this tutorial, I will create a user service through the command below.


ng generate service user

After creating the service then I will create many methods like getUsers(), getUser(), addUser(), updateUser(), and deleteUser().


// src/app/user.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class UserService {

  private apiUrl = 'http://localhost:3000/users';

  constructor(private http: HttpClient) { }

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

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

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

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

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