Angular forms with GitHub example — tutorial 4: posting form data using API

So far in these series of tutorials, I have introduced how to create a basic form in Angular, style it using Angular material and Bootstrap, and use two-way data binding to capture user data.

Now in this tutorial I’m gonna teach you how to post the data we captured from the users over the internet using API and data service. A data service compresses all HTTP access so it won’t be placed in components directly. In any practical web application, there might be several components that need to reach out using HTTP to the API. Take our details-form component as an example. It contains a form to capture user’s personal information that needs to be stored (post data). If the process of establishing a connection over HTTP is implemented in that component, then we need to copy paste the same code in any other component that might need HTTP access or if we make a change in data access, say changing server environment that leads to change in API endpoints, requires a massive modification of the code base. For these reasons and to adhere to DRY principle, we need to create a separate data access service.

So go to the app folder and create a folder and call it “services” and then create a file called “data.seervice.ts” or alternatively use CLI by entering below command. I encourage you to use CLI for this as it creates a test file along with the service:

ng g service services/data

if you have created an empty file, you need to add below code inside data service but if you used CLI this code should be there

import { Injectable } from '@angular/core';@Injectable({providedIn: 'root'})export class DataService {constructor() { }}

GitHub code commit

If you notice, the data service uses injectable decorator that is provided in the root of the Angular-form application and that’s what we need because otherwise we needed to add the service to providers in the app module. So inside DataService class we need a post form method that uses HTTP to post the “Person” object that has been populated with the user data.

postUserDetails(person: Person){}

GitHub code commit

next we need to fill up the method and return a value that indicates if the method successfully posted data to the API endpoint or faile. If failed what was the reason. In Angular this process is handled by observables. We import observables from RxJS package and we’ll pass the Person class to it.

postUserDetails(person: Person): Observable<Person>{return<Person>('ApiUrl', person)}

GitHub code commit

Now we need to call this method from our details-form component. Lets open up TypeScript file inside details-form component and import the data service there. By importing data service in constructor, the whole class will have access to it easily. Now we are going to replace stuff inside onDetailsFormSubmit method with the service call and pass this.person object that caries user’s personal data in it. Inside subscription, I’m using the arrow function to present first, successful call and second, unsuccessful call. You might need to notify the user with making a checkmark appear to say the post has been successful or a red stop sign to say it hasn’t been. For now lets just put it in the console.

onDetailsFormSubmit(){this.dataService.postUserDetails(this.person).subscribe(person => {console.log('postUserDetails has been successful:' + person)});error => {console.log ('postUserDetails post failed: '+ error)}}

GitHub code commit

Now if you run the code, you’ll see console showing below error:

ERROR NullInjectorError: StaticInjectorError(AppModule)[HttpClient]:

StaticInjectorError(Platform: core)[HttpClient]:

This means HTTP client used inside data service is not imported in the app module. We just need to go to the app.module.ts file and add “HttpClientModule” to import part of the module.

GitHub code commit

Now the form is up and running but pressing save details button doesn’t do anything and console shows below errors:

That’s because we don’t have a working API endpoint yet. So head back to our service and add check to see if we are in development environment. If yes, just pass a static Person object to show the method has been successfully called and if we are in any other environment, call respective API endpoints. But that’s the topic of my next tutorial. For now we just return the person object passed to the method.

postUserDetails(person: Person): Observable<Person>{// return<Person>('ApiUrl', person)return of(person)}

GitHub code commit

This tutorial is part of a series of tutorials on Angular form. if this is the first time you are seeing my tutorial, please have a look at my first tutorial on creating basic forms in Angular and then form styling in Angular and two-way data binding. The project code is here in my personal GitHub page and you can see a full demo on StackBlitz

Feel free to reach out to me if you have any questions.

Ramin Ahmadi

Written by

Ramin Ahmadi

Full stack front-end developer. I make it a goal to automate myself out of routine tasks. My motto is, ‘write human readable code, lean and clean’.

Ramin Ahmadi
I am a full-stack front end developer with over 5 years experience in web design and development. I have worked with a wide variety of environments and languages including Angular, TypeScript, NodeJS, Restful API, Microservices, Atomic design, JQuery, Material design, Progressive Web Apps, DevOps, and many Azure tools. I make it a goal to automate myself out of routine tasks in my daily work. My motto is, ‘write human readable code, lean and clean’.

Comments 0

Your email address will not be published. Required fields are marked *

Angular forms with GitHub example — tutorial 4: posting form data using API

log in


reset password

Back to
log in
Font Resize
Choose A Format
Trivia quiz
Series of questions with right and wrong answers that intends to check knowledge
Voting to make decisions or determine opinions
The Classic Internet Listicles
Photo or GIF
GIF format