Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Angular httpclient post example

Suggested Videos
Part 65 - Angular httpclient get example | Text | Slides
Part 66 - Angular httpclient error handling | Text | Slides
Part 67 - Handling angular resolver errors | Text | Slides

In this video we will discuss posting data to the server using Angular HttpClient service.


To issue a POST request to the server, we use HttpClient service post() method.


Modify code in save() method in employee.service.ts file as shown below.

save(employee: Employee): Observable<Employee> {
    if (employee.id === null) {
        // const maxId = this.listEmployees.reduce(function (e1, e2) {
        //     return (e1.id > e2.id) ? e1 : e2;
        // }).id;
        // employee.id = maxId + 1;
        // employee.id = 0;

        // this.listEmployees.push(employee);
        return this.httpClient.post<Employee>('http://localhost:3000/employees',
            employee, {
                headers: new HttpHeaders({
                    'Content-Type': 'application/json'
                })
            })
            .pipe(catchError(this.handleError));
    } else {
        const foundIndex =
            this.listEmployees.findIndex(e => e.id === employee.id);

        this.listEmployees[foundIndex] = employee;
    }
}

Code Explanation : 
  • save() method does 2 things. Creates a new employee and updates an existing employee.
  • If the incoming employee object id property is null, then we know it's a new employee 
  • The code to compute employee id is commented. We no longer need to compute the id of the new employee on the client side. The server will do this.
  • We use the post() method of the HttpClient service to issues a POST request to the server.
  • We are using the generic parameter of the post<T> method to specify the type the post() method returns after a successful post. Upon a successful post, the server returns an observable of the same type, in our case an Observable<Employee>
  • The returned Observable will contain the created employee object. This returned object will also have the values for server assigned properties. In our case the id of the employee object is populated by the server.
  • Since the post<Employee>() method returns an Observable<Employee>, we have set the return type of the save() method as such.
Angular HttpClient post parameters : HttpClient post() method has the following 3 parameters

Parameter Purpose
url The URL to which the data must be posted
body The data to post to the server
options Request options if any. On common piece of data that we send to the server using options parameter is the content-type header

Notice, we are using the pipeable operator (catchError) to handle errors. 

Please ignore the code in else block. This block is executed when updating an existing employee. We will discuss updating data using the put() method in our next video.

Modify code in saveEmployee() method in create-employee.component.ts file as shown below.

saveEmployee(empForm: NgForm): void {
  this._employeeService.save(this.employee).subscribe(
    (data: Employee) => {
      // log the employee object after the post is completed
      console.log(data);
      empForm.reset();
      this._router.navigate(['list']);
    },
    (error: any) => { console.log(error); }
  );
}

Next video : Updating data using HttpClient service

angular crud tutorial

2 comments:

It would be great if you can help share these free resources