We've learned that it's best practice to let controllers in Angular just handle the view and to move logic about acquiring data into services. Today we'll put those best practices into practice by refactoring part of a book app! We'll refactor code to move AJAX requests out of the controller, and we'll practice using promises.
Note: Services are a best practice, but they're not required to make a working Angular app. If you're looking for a quick and dirty mockup, you may not need services.
- Start the server (use
budo -P --open
). - Open your browser. Open your JavaScript console. Verify which features of the site are working and which aren't. You should see:
- Working: index, show, delete for books
- Not working: update for books You should see an error in the browser console
- Examine the
BooksIndexController
- observe that it does not use$http
. Instead, it uses aBookService
service. - Find the code for this service. How is it connected to the controller?
- Take a look at
BookService
, especially itsquery
method. Notice how it is handling$http
requests for the controller.
- Add the
BookService
service to yourBooksShowController
as a dependency.
Hey! You just fixed update! (That one was already implemented with the service for you.)
-
Refactor the
getBook
method inBooksShowController
to NOT use$http
; instead, it should useBookService.get(id)
. That function returns a promise, so remember to specify what happens.then
.It might be helpful to look at the
BooksIndexController
or theupdateBook
method in this controller. The book service returns only the requested book when it resolves the promise. Log the returned value to the console to see the exact format. -
When you're done refactoring this code, the page should still work. Use CMD+SHIFT+R to refresh and clear the browser's cache.
- The book service has everything implemented except
remove
. Editbook.service.js
to complete theremove
method.
Hint: Take a look at the other methods in the service. They all follow a very similar pattern.
-
Update the books show controller to remove the final remaining call to
$http
- use your updatedremove
method fromBookService
. -
Check that everything works.
Many sites employ RESTful conventions, so they serve things in very similar ways. The module ngResource
implements a service very similar to the one we just built! If you're using a RESTful API, you can often replace $http
with ngResource
.
Check the ngResource
solution branch to compare, and/or check out this resource on $resource
: http://www.sitepoint.com/creating-crud-app-minutes-angulars-resource/