Submodule 23.3: Sending data to the server

Site: ΕΛ/ΛΑΚ Moodle
Course: Study / Web Design and Web Development
Book: Submodule 23.3: Sending data to the server
Printed by: Guest user
Date: Thursday, 21 November 2024, 10:31 PM

Description

  • HttpClient.get
  • HttpClient.post

Introduction

In this submodule, you will learn to send and store the form values into the db.json, so they are available any time.

You will learn how to persist changes in the data back to the server. You will use the HttpClient.post method available on objects to save the feedback submitted by users to the server.

Update feedback.service.ts

Update feedback.service.ts as follows:

addFeedbacks(fb: Feedback): Observable<Feedback[]> {
  return this.http.post<Feedback[]>(baseURL + 'feedback', fb);
}

HttpClient.post constructs an Observable with configured POST request and when the Observable instance is subscribed, POST request is executed on the server.

In HttpClient.post method we need to pass URL, request body and optional http options such as headers, response type etc.  

The addFeedbacks method is similar with what we have used in the getFeedbacks(). The difference is that here we use post instead of get. Using this we can store the fb form group in the JSON file as a new member of the feedback array. 

Update the contact.component.ts

Update the contact.component.ts file as follows:

this.feedBackService.addFeedbacks(this.fb).subscribe(fb => this.feedbacks.push(this.fb));

Note that here we use push. We do this because we don't just take the existing values of the JSON file but we are adding new ones.

The results

With the previous code configured, open your Terminal, go to the jsonServer  sub-folder and run json-server --watch db.json -d 2000. This will introduce a delay of 2 seconds before the server sends the reply for the request. The server will serve the db.json file for your application. You can watch the server in your browser  URL localhost:3000 

Open another Terminal window, go to the angularChocoYourname  angular-sub-folder and run ng serve to run your application in development mode. In your browser navigate to the URL localhost:4200 

The contact page has been server by the json-server. 

We have stored the data in the db.json file and we can access these every time!

Do a Git commit with the message "Angular storing data".