Exercise 32: Services - jkneal/spring-angular-train GitHub Wiki
Goals
Learn how to use built in services and create custom services
Instructions
- In app.js, create a constant with name ‘ProductServiceUrl’ and value 'http://localhost:8080/inventory' within the ‘storeApp’ module
- In
angular/scripts, create a new directory named 'services' - In the services directory, create a new file named product-services.js
- In product-services.js, create a new service named ‘ProductService’ that belongs to the ‘storeApp’ module. The service should take the following services as arguments: '$http', '$log', 'ProductServiceUrl'
- In the product service, add the following methods:
- getAllProducts() – first log the string ‘retrieving all products’, then using the $http get method invoke the URL given by ProductServiceUrl to return all products on the server (return the promise object from the $http get call)
- addProduct(product) – first log the string ‘adding product ‘ followed by JSON.stringify(product), then using the $http put method invoke the URL given by ProductServiceUrl + '/add'. Pass the product as put data. Return the promise object from the $http post call
- removeProduct(id) – first log the string 'removing product with id ' followed by id (the argument). Then using the $http delete method invoke the URL given by ProductServiceUrl + ‘/’ + id (argument). Return the promise object from the $http post call
- In store-controller.js, initialize the ‘products’ scope property by invoking the product service’s ‘getAllProducts’ method
- Next, modify the scope method ‘addProduct’ to invoke the product service’s ‘addProduct’ method (create a new product from the arguments to pass to the service method). If the call is successful, update the scope ‘products’ property from the return data and set the scope property ‘productAdded’ to true
- Finally, modify the scope method ‘removeProduct’ to invoke the product service’s ‘removeProduct’ method (passing the index argument). If the call is successful, update the scope ‘products’ property from the return data
VERIFICATION
- Start the training application and go to the app home page
- Click on the link 'Angular Exercises'
- Verify two products are listed in the products table
- Check the server console (command prompt) and verify the message ‘getting all products on server’ appears. Likewise check the browser console for the message ‘retrieving all products’
- Add a new product and verify the product appears in the products table and the successful message is displayed
- Check the server console (command prompt) and verify the message ‘add new product on server: …’ appears. Likewise check the browser console for the message ‘adding product …’
- Delete a product from the products table and verify it is removed
- Check the server console (command prompt) and verify the message ‘deleting product on server with index: …’ appears. Likewise check the browser console for the message