This post explains how we can make an HTTP POST in Angular application, to an API which is exposed as a web service. This is a continuation of the previous example HTTP GET in Angular -Asp.Net MVC Application. You can download the source code from here. In the source code, please refer to 4_Angular_Http_POST project.
Edit app.module.ts and import FormsModule from angular/forms.
1 |
import { FormsModule } from '@angular/forms'; |
Below is the updated app.module.ts file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { HttpModule } from '@angular/http'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { routing } from './app.routing'; import { HomeComponent } from '../Home/home.component'; import { AddEmployeeComponent } from '../Employee/add-employee.component'; import { ListEmployeesComponent } from '../Employee/list-employees.component'; import { AddProductComponent } from '../Product/add-product.component'; import { ListProductsComponent } from '../Product/list-products.component'; @NgModule({ imports: [ BrowserModule, routing, HttpModule, FormsModule ], declarations: [ AppComponent, HomeComponent, AddEmployeeComponent, ListEmployeesComponent, AddProductComponent, ListProductsComponent ], bootstrap: [AppComponent] }) export class AppModule { } |
Add a new file ‘add-employee.component.html’ in Angular\Employee folder. This is the template for add-employee component. The contents of the file is as below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<form> <div class="form-group"> <label for="firstName">First Name</label> <input type="text" class="form-control" name="firstName" [(ngModel)]="employee.FirstName" placeholder="first name"> </div> <div class="form-group"> <label for="lastName">Last Name</label> <input type="text" class="form-control" name="lastName" [(ngModel)]="employee.LastName" placeholder="last name"> </div> <div class="form-group"> <label for="city">City</label> <input type="text" class="form-control" name="city" [(ngModel)]="employee.City" placeholder="city"> </div> <div class="form-group"> <label for="country">Country</label> <input type="text" class="form-control" name="country" [(ngModel)]="employee.Country" placeholder="country"> </div> <button type="submit" (click)="addEmployee(employee)" class="btn btn-primary">Submit</button> <div><label>{{message}}</label></div> </form> |
Specify the template url in add-employee component.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import { Component, OnInit } from '@angular/core'; import { Employee } from './employee'; @Component({ selector: 'add-employee', templateUrl: 'AngularApp/Angular/Employee/add-employee.component.html', }) export class AddEmployeeComponent implements OnInit { message: string; employee: Employee = new Employee(); ngOnInit(): void { this.message = 'Enter Employee Details and Save'; } addEmployee(employee: Employee) { console.log(employee); } } |
Navigate to Employee/AddEmployee link and you can see page.
Edit EmployeeAPIController and add HTTP Post method to save employee.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
[HttpPost] [Route("EmployeeService/SaveEmployee")] public IHttpActionResult SaveEmployee(EmployeeModel employee) { try { IEmployeeRepository employeeRepo = new EmployeeRepository(new CodifyDataContext()); EmployeeEntity empEntity = new EmployeeEntity(); empEntity.Address = employee.Address; empEntity.City = employee.City; empEntity.Country = employee.Country; empEntity.FirstName = employee.FirstName; empEntity.LastName = employee.LastName; empEntity.CreatedBy = System.Environment.UserName; empEntity.ModifiedBy = System.Environment.UserName; empEntity.CreatedDate = DateTime.Now; empEntity.ModifiedDate = DateTime.Now; employeeRepo.AddEmployee(empEntity); employeeRepo.SaveChanges(); return Ok("Success"); } catch (Exception ex) { return Ok(ex.Message); } } |
Add a new method for saveEmployee in employee.service.ts
1 2 3 4 5 6 7 8 9 10 |
saveEmployee(employee: Employee): Observable<string> { let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this.http.post(this.employeeServiceURL + 'SaveEmployee', JSON.stringify(employee), options) .map(this.extractData) .catch(this.handleError); } |
Modify add-employee.component.ts and call employeeService to save new employee.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import { Component, OnInit } from '@angular/core'; import { Employee } from './employee'; import { EmployeeService } from './employee.service'; @Component({ selector: 'add-employee', templateUrl: 'AngularApp/Angular/Employee/add-employee.component.html', providers: [EmployeeService] }) export class AddEmployeeComponent implements OnInit { message: string; employee: Employee = new Employee(); constructor(private employeeService: EmployeeService) { } ngOnInit(): void { this.message = 'Enter Employee Details and Save'; } addEmployee(employee: Employee) { console.log(employee); if (!employee) { return; } this.employeeService.saveEmployee(employee) .subscribe( message => this.message = message, error => this.message = <any>error); } } |
Navigate to Employee/Add Employee link. Enter employee details in the form and click on submit.
If everything goes well you get a Success message.
One comment on “Angular HTTP POST in ASP.Net MVC Application”