Skip to content

This application demonstrates Angular http requests - get, post, put and delete

Notifications You must be signed in to change notification settings

chilupa/angular-http

Repository files navigation

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:

AngularHttp

This project was generated with Angular CLI version 6.0.7.

Development server

Run ng serve for a dev server. Navigate to http://localhost:4200/. The app will automatically reload if you change any of the source files.

About

This application demonstrates Angular http requests - get, post, put and delete

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published