Posting Data Using a Service4:33 with Andrew Chalkley
Finally, we'll post the data from the form to a mock back-end server.
Finally, let's post the data to the server. 0:00 Since we're working with promises, we can post the data to the server and 0:03 then, on success, emit the event to add the comment and reset the form. 0:08 We can create a new method in the entry service to add a comment. 0:13 This method will take an entry ID, which is a number, and a comment to object. 0:24 Then it will post the comment to the server. 0:52 And then return a promise. 1:11 Like I said before, this in memory API is just for the purposes of this course. 1:17 We can't expect this data to persist anywhere meaningful, 1:23 we're simply going to post it and assume everything went well. 1:26 In the entry-comment-form.component.ts file, we'll need to input the entry 1:30 service before we can use our new add comment method. 1:35 Right above the onSubmit method, add a constructor function. 1:39 With the parameter entryServiceof type EntryService. 1:54 Then we need to import the entryService for the type definition. 2:03 Add the private keyword before the parameter. 2:24 Specifying private tells TypeScript to append the variable to the prototype 2:26 during the transpolation process, making available on the instance of the class. 2:31 In the onSubmit method, we can call our addComment method. 2:37 Then, we'll put the event meter and 2:47 the form reset inside the success callback of the promise. 2:50 We need to add the entryId property and have the entry components set the value. 3:07 First, we must import the input decorator so 3:13 that the entry component can pass the value on to the common form component. 3:16 Then add the entryId, 3:22 On the form component. 3:31 Finally, set the entryId value on the app-entry-comment-form element. 3:33 Because we're binding to the entryId property on the entry-comment-form 3:45 component, we will use the square brackets. 3:49 Then we set the expression to entry.id. 3:54 Data is flowing one way, from the parent component, 4:00 the entry component, to the child component, the form component. 4:03 Okay, let's take a look. 4:08 Everything appears to be working correctly. 4:22 We've got our form wired up and it's posting data to our mock back end. 4:25 In the next stage, we'll dive deeper into form validation. 4:29
You need to sign up for Treehouse in order to download course files.Sign up