forked from angular/code.angularjs.org
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstep_11.html
175 lines (132 loc) · 7.48 KB
/
step_11.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
<h1>Tutorial: 11 - REST and Custom Services</h1>
<div class="tutorial-11-rest-and-custom-services"><ul doc:tutorial-nav="11"></ul>
<p>In this step, you will improve the way our app fetches data.</p><doc:tutorial-instructions step="11"></doc:tutorial-instructions><p>The last improvement we will make to our app is to define a custom service that represents a <a href="http://en.wikipedia.org/wiki/Representational_State_Transfer">RESTful</a> client. Using this client we
can make xhr requests for data in an easier way, without having to deal with the lower-level <a href="#!/api/angular.service.$xhr"><code>$xhr</code></a> API, HTTP methods and URLs.</p>
<p>The most important changes are listed below. You can see the full diff on <a href="https://github.com/angular/angular-phonecat/compare/step-10...step-11">GitHub</a>:</p>
<h3>Template</h3>
<p>The custom service is defined in <code>app/js/services.js</code> so we need to include this file in our layout
template:</p>
<p><strong><code>app/index.html</code>.</strong></p><div ng:non-bindable><pre class="brush: js; html-script: true;">
...
<script src="js/services.js"></script>
...
</pre></div><h3>Service</h3>
<p><strong><code>app/js/services.js</code>.</strong></p><div ng:non-bindable><pre class="brush: js;">
angular.service('Phone', function($resource) {
return $resource('phones/:phoneId.json', {}, {
query: {method: 'GET', params: {phoneId: 'phones'}, isArray: true}
});
});
</pre></div><p>We used the <a href="#!/api/angular.service"><code>api/angular.service</code></a> API to register a custom service. We passed in the name of
the service - 'Phone' - and a factory function. The factory function is similar to a controller's
constructor in that both can declare dependencies via function arguments. The Phone service
declared a dependency on the <code>$resource</code> service.</p>
<p>The <a href="#!/api/angular.service.$resource"><code><code>$resource</code></code></a> service makes it easy to create a <a href="http://en.wikipedia.org/wiki/Representational_State_Transfer">RESTful</a> client with just a few lines
of code. This client can then be used in our application, instead of the lower-level <a href="#!/api/angular.service.$xhr"><code>$xhr</code></a> service.</p>
<h3>Controller</h3>
<p>We simplified our sub-controllers (<code>PhoneListCtrl</code> and <code>PhoneDetailCtrl</code>) by factoring out the
lower-level <a href="#!/api/angular.service.$xhr"><code>$xhr</code></a> service, replacing it with a new service called
<code>Phone</code>. Angular's <a href="#!/api/angular.service.$resource"><code><code>$resource</code></code></a> service is easier to use than
<a href="#!/api/angular.service.$xhr"><code>$xhr</code></a> for interacting with data sources exposed as RESTful
resources. It is also easier now to understand what the code in our controllers is doing.</p>
<p><strong><code>app/js/controllers.js</code>.</strong></p><div ng:non-bindable><pre class="brush: js;">
...
function PhoneListCtrl(Phone) {
this.orderProp = 'age';
this.phones = Phone.query();
}
//PhoneListCtrl.$inject = ['Phone'];
function PhoneDetailCtrl(Phone) {
var self = this;
self.phone = Phone.get({phoneId: self.params.phoneId}, function(phone) {
self.mainImageUrl = phone.images[0];
});
...
}
//PhoneDetailCtrl.$inject = ['Phone'];
</pre></div><p>Notice how in <code>PhoneListCtrl</code> we replaced:</p>
<pre><code>$xhr('GET', 'phones/phones.json', function(code, response) {
self.phones = response;
});
</code></pre>
<p>with:</p>
<pre><code>this.phones = Phone.query();
</code></pre>
<p>This is a simple statement that we want to query for all phones.</p>
<p>An important thing to notice in the code above is that we don't pass any callback functions when
invoking methods of our Phone service. Although it looks as if the result were returned
synchronously, that is not the case at all. What is returned synchronously is a "future" — an
object, which will be filled with data when the xhr response returns. Because of the data-binding
in angular, we can use this future and bind it to our template. Then, when the data arrives, the
view will automatically update.</p>
<p>Sometimes, relying on the future object and data-binding alone is not sufficient to do everything
we require, so in these cases, we can add a callback to process the server response. The
<code>PhoneDetailCtrl</code> controller illustrates this by setting the <code>mainImageUrl</code> in a callback.</p>
<h3>Test</h3>
<p>We have modified our unit tests to verify that our new service is issuing HTTP requests and
processing them as expected. The tests also check that our controllers are interacting with the
service correctly.</p>
<p>The <a href="#!/api/angular.service.$resource"><code>$resource</code></a> service augments the response object with
methods for updating and deleting the resource. If we were to use the standard <code>toEqual</code> matcher,
our tests would fail because the test values would not match the responses exactly. To solve the
problem, we use a newly-defined <code>toEqualData</code> <a href="http://pivotal.github.com/jasmine/jsdoc/symbols/jasmine.Matchers.html">Jasmine matcher</a>. When the
<code>toEqualData</code> matcher compares two objects, it takes only object properties into account and
ignores methods.</p>
<p><strong><code>test/unit/controllersSpec.js</code>:</strong></p><div ng:non-bindable><pre class="brush: js;">
describe('PhoneCat controllers', function() {
beforeEach(function(){
this.addMatchers({
toEqualData: function(expected) {
return angular.equals(this.actual, expected);
}
});
});
describe('PhoneListCtrl', function() {
var scope, $browser, ctrl;
beforeEach(function() {
scope = angular.scope();
$browser = scope.$service('$browser');
$browser.xhr.expectGET('phones/phones.json')
.respond([{name: 'Nexus S'}, {name: 'Motorola DROID'}]);
ctrl = scope.$new(PhoneListCtrl);
});
it('should create "phones" model with 2 phones fetched from xhr', function() {
expect(ctrl.phones).toEqual([]);
$browser.xhr.flush();
expect(ctrl.phones).toEqualData([{name: 'Nexus S'},
{name: 'Motorola DROID'}]);
});
it('should set the default value of orderProp model', function() {
expect(ctrl.orderProp).toBe('age');
});
});
describe('PhoneDetailCtrl', function() {
var scope, $browser, ctrl;
beforeEach(function() {
scope = angular.scope();
$browser = scope.$service('$browser');
});
beforeEach(function() {
scope = angular.scope();
$browser = scope.$service('$browser');
});
it('should fetch phone detail', function() {
scope.params = {phoneId:'xyz'};
$browser.xhr.expectGET('phones/xyz.json').respond({name:'phone xyz'});
ctrl = scope.$new(PhoneDetailCtrl);
expect(ctrl.phone).toEqualData({});
$browser.xhr.flush();
expect(ctrl.phone).toEqualData({name:'phone xyz'});
});
});
});
</pre></div><p>To run the unit tests, execute the <code>./scripts/test.sh</code> script and you should see the following
output.</p>
<pre><code>Chrome: Runner reset.
....
Total 4 tests (Passed: 4; Fails: 0; Errors: 0) (3.00 ms)
Chrome 11.0.696.57 Mac OS: Run 4 tests (Passed: 4; Fails: 0; Errors 0) (3.00 ms)
</code></pre>
<h2>Summary</h2>
<p>There you have it! We have created a web app in a relatively short amount of time. In the <a href="#!/tutorial/the_end">closing notes</a> we'll cover were to go from here.</p>
<ul doc:tutorial-nav="11"></ul></div>