sf-wdi-31 / angular-services-training

[angular, service, $http, training, promises, javascript]

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Angular Services Training

Overview

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.

Investigate Existing Code

  1. Start the server (use budo -P --open).
  2. 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
  3. Examine the BooksIndexController - observe that it does not use $http. Instead, it uses a BookService service.
  4. Find the code for this service. How is it connected to the controller?
  5. Take a look at BookService, especially its query method. Notice how it is handling $http requests for the controller.

Refactor

  1. Add the BookService service to your BooksShowController as a dependency.

Hey! You just fixed update! (That one was already implemented with the service for you.)

BooksShowController, getBook

  1. Refactor the getBook method in BooksShowController to NOT use $http; instead, it should use BookService.get(id). That function returns a promise, so remember to specify what happens .then.

    It might be helpful to look at the BooksIndexController or the updateBook 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.

  2. When you're done refactoring this code, the page should still work. Use CMD+SHIFT+R to refresh and clear the browser's cache.

BookService, remove & BooksShowController, deleteBook

  1. The book service has everything implemented except remove. Edit book.service.js to complete the remove method.

Hint: Take a look at the other methods in the service. They all follow a very similar pattern.

  1. Update the books show controller to remove the final remaining call to $http - use your updated remove method from BookService.

  2. Check that everything works.

ngResource

Many sites employ RESTful conventions, so they serve things in very similar ways. What if we could reuse a service like this for any API with RESTful routes?

It turns out the Angular community thought of that a long time ago. 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/

About

[angular, service, $http, training, promises, javascript]


Languages

Language:JavaScript 75.7%Language:HTML 24.3%