Use HttpClient for POST, PUT and DELETE calls - lordoftheflies/angular-essential-training GitHub Wiki
Using the angular HTTP client post and delete methods, are similar to how you use the get method. Let's update the media item service class to make post and delete calls, using the HTTP client service for the ad call, we are going to return a call to HTTP posts. (typing) The post method takes in a URL string as the first parameter. So he set that to the media items, URL that the mock backend supports. (typing) The second parameter is the body of the post, the HTTP client methods, support passing different data types to them, and they will auto detect the content type and handle setting the content type header. So we can pass in the media item as is, and the underlying code will detect it as an object and set the content type header to application slash Jason. Now we can switch over to the media dash item dash form dot component dot Ts file, and we can refactor the on submit methods. This is already calling the media item service dot add method, which prepares the observable, but we need to subscribe to the return of that to kick it off. So we add dot subscribe. (typing) Okay, that's implement the delete call, back over in the media dash item dot service dot Ts file. We can update the delete method to return a call to this dot HTTP dot delete. (typing) The HTTP dot delete method needs a URL and our mock backend will support media items slash ID. So let's use the back ticks here and build the string with the media items slash string, and a variable replacement for the media item.id property from the media item passed in. (typing) The dollar sign and curly braces here are how we tell the string interpolation to put our variable in the string build-out. And now that we have all the service methods using the HTTP client, we can remove the class property for media items. Okay, now we just need to update where the service method is being used, over in the media dash item dash list dot component dot Ts file. In the on media item delete method, that's at a call to dot subscribe. (typing) And Let's pass this one, a function so we can trigger a reload of the list on delete so we can create an error function. And since we don't need to deal with the parameters at this time, we can use an empty parentheses for that. In the functional block we can call this dot get media item passing in this dot medium. (typing) And if we switch over to the browser, We can remove items and see the delete inaction. But if we add an item, we don't see it in the list right away. This is because the form component is separate from the list component. So the list doesn't know when to update, but if we click one of the medium filter links, we can see the ad did create the new data VR HTTP post-call we added. The list Update issue will be handled when we get into the lessons on routing.