Skip to content
Pavan Chilukuri edited this page Sep 27, 2018 · 1 revision

CRUD Operations in Angular 6 using HTTP requests

In this application, I've used HttpClient's methods - get, post, put and delete to perform CRUD operations on the mock json data which is run locally with json-server at http://localhost:3000/users

Why write a Service?

In Angular application, it is always a best practice to separate data presentation logic usually written in a Component and data access logic written in a Service.

Services are available to all classes and could be injected in any class throughout our application. Hence, it is good to write the data access logic in a Service (shown below)

Making a GET request

  getUsers(): Observable<User> {
    return this.http.get<User>(this.url);
  }

Making a POST request

  postUsers(user): Observable<User> {
    return this.http.post<User>(this.url, user, this.httpOptions);
  }

Making a PUT request

  updateUser(userId, user): Observable<User> {
    const putUrl = this.url + '/' + userId;
    return this.http.put<User>(putUrl, user, this.httpOptions);
  }

Making a DELETE request

  deleteUser(userId): Observable<{}> {
    const deleteUrl = this.url + '/' + userId;
    return this.http.delete(deleteUrl, this.httpOptions);
  }

A note which is to be worth remembered.

Always subscribe!

An HttpClient method does not begin its HTTP request until you call subscribe() on the observable returned by that method. This is true for all HttpClient methods.

Useful Links: