Performing CRUD Operations

In this lesson, we will look at performing HTTP operations in Angular either with a mock or real API.

In the previous lesson, we created a data store using the in-memory-web-api and returned that data from the store using a service. This returned data now can be used to perform the API operations.

We will use an Angular service to obtain the data and store it and share it with the components that need the data.

As we discussed in the first lesson of this section, Angular has HttpClient package that we use for performing AJAX calls.

  providedIn: 'root'
export class DataService {

  apiurl = 'api/users';                 // Our created Data can be accessed here at api/users
  headers = new HttpHeaders().set('Content-Type', 'application/json').set('Accept', 'application/json');
  httpOptions = {
    headers: this.headers

constructor(private http: HttpClient) { }                     
//Injecting HTTP service to communicate with the data

We create a singletons service here that is responsible for performing HTTP operations and getting us the required data.

Importing the module

The first step is to import the HttpClientModule inside the root module. And now we would be able to use HttpClient, HttpHeaders inside the service.

Inside the service, we are accessing the data through the remote API with the help of this line.

apiurl = 'api/users';

The next step is to inject the service HttpClient but before that, we need to import some files.

import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Observable, throwError} from 'rxjs';
import { tap, catchError } from 'rxjs/operators';

Injecting the service

constructor(private http: HttpClient) { }  

And we are all set to perform the CRUD operations now.


Get hands-on with 1000+ tech skills courses.