Angular forms with GitHub example — tutorial 5: posting form data and error handling


Let’s see, in this series of tutorials, I have introduced how to create a basic form in Angular, style it using Angular material and Bootstrap, use two-way data binding to capture user data and posting data using HTTP.

In this tutorial we are going to discuss post form data to a real HTTP API endpoint by using a web service. When you develop a website for a real organization, they will provide you with more than one API endpoint. A simple set up could be API endpoints for testing environment, which is where you develop the code, staging environment that contains the latest release candidate and production environment where your web app is hosted. For the sake of this tutorial , we are going to use a very popular web service called RutsReq where you can send requests at endpoints that you have designed there and expect to see a response that you have determined for the request. This transaction replicates real API behaviour which is exactly what we need for this tutorial.

Now lets go to https://putsreq.com/ and click on putsReq button

In the next page, PutsReq gives you a URL and a space to write your response. This is usually where API performs a database related task, e.g add a new person, and then responds that the task was successful or not due to a reason. So lets assume that our API is successful in performing a hypothetical task and needs to send a response. Lets put below code in Response Builder section.

var person = JSON.parse(request.body);response.body = person;

This basically returns the same object that our details-form produced and returns it to the app with a successful message. But first we need to indicate that our API url is PutsReq URL just go ahead and copy it from the website.

And then paste it in data service method. For now we are going to comment out static response and use real API.

postUserDetails(person: Person): Observable<Person>{return this.http.post<Person>('https://putsreq.com/aEJaJyGeFRl7vzOj00sb', person)//return of(person)}

GitHub code commit

Now lets head back to our website and see if the post method works as expected. But first lets get rid of default values on ngOnInit(), so that we can see entered values by the user.

ngOnInit() {// populating age array with 1 to 100this.ages = Array(100).fill(1).map((e,i)=>i+1);}

GitHub code commit

As you can see the response from PutsReq has been successful. Lets head back to their website to see if it shows any record of our post request there.

Yup, it’s there. Request header details, post object and what has been responded from API.

Now we need a nice prompt to tell the user that post has been successful. I’m thinking showing a snackbar message with person’s first name and last name plus “successfully saved”.

Let’s add it to our app module.

GitHub code commit

Then let’s add snackbar message to success post on form submit method.

onDetailsFormSubmit(){this.dataService.postUserDetails(this.person).subscribe(person => {console.log('postUserDetails has been successful:', person)let message = person.firstName + '' + person.lastName + ' saved successfully';this._snackBar.open(message,null, {duration: 2000,});});error => {console.log ('postUserDetails post failed: ', error)}}

GitHub code commit

And lo and behold, we have our snackbar message. I don’t know about you but I don’t really like how it looks. Let’s see if we can introduce our own snackbar component, where we get to change font details and background color or even a nice little tick mark to indicate that it’s a happy message.

So let’s create a new folder and name it components, we are going to put our reusable components there then use below command in terminal:

ng g c components/notification

this will create a custom component which we are going to use inside the snackbar.

GitHub code commit

Now let’s go to the details form component and change snakbar method from open to openFromComponent and include newly created NotificationComponent to it.

onDetailsFormSubmit(){this.dataService.postUserDetails(this.person).subscribe(person => {console.log('postUserDetails has been successful:', person)let message = person.firstName + ' ' + person.lastName + ' saved successfully';this._snackBar.openFromComponent(NotificationComponent, {data: {message: message,success: true},duration: 3000,});});error => {console.log ('postUserDetails post failed: ', error)}}

This calls our notification component and uses data object to pass data to the component. Because we are creating a reusable component, we might need to pass different types of message to it so we need a data object that contains the message and type of it. Then in the component itself, we just create a placeholder with 2 separate designs for success or failure. Doing that we don’t need to create yet another component for failure cases.

And then let’s go to notification component typescript file and use an injector to receive data that has been sent while component being called. Then inside the notification component, access data object to show it.

<span class="notification">{{data.message}}</span>

GitHub code commit

Next add a data model for data object used in notification component so everything is strongly type.

Create a sub-folder in data-model folder and call it components, where we are going to keep all reusable component related data models.

export class NotificationData {message: string;success: boolean;}

GitHub code commit

Finally, change notification component to cater for success and fail. First we need to use a ngClass to assign a specific class to the wrapper based on success property.

<span class="notification" *ngIf="data" [ngClass]="data.success ? 'notification__success' :'notification__fail'">{{data.message}}</span>

Then we define an alert color in our color palette the same way we defined for primary and secondary variables. If you are confuse just have a look at my second tutorial on form styling. Just a reminder that because we use variables, we need to import them to notification’s style file by @import :

@import './../../../assets/scss/variables.scss';.notification{&__success{color: $color-tritary;}&__fail{color:$color-alert;}}

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, two-way data binding and posting form data using API. The project code is here in my personal GitHub page https://github.com/ramin-ahmadi/angular-forms and you can see a full demo on StackBlitz https://stackblitz.com/github/ramin-ahmadi/angular-forms

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 5: posting form data and error handling

log in

Captcha!

reset password

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