forked from angular/code.angularjs.org
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathangular.service.$resource.html
195 lines (176 loc) · 10 KB
/
angular.service.$resource.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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
<h1>angular.service.$resource</h1>
<div class="angular-service-resource"><fieldset class="workInProgress"><legend>Work in Progress</legend>
This page is currently being revised. It might be incomplete or contain inaccuracies.</fieldset>
<h2>Description</h2>
<div class="description"><p>A factory which creates a resource object that lets you interact with
<a href="http://en.wikipedia.org/wiki/Representational_State_Transfer">RESTful</a> server-side data sources.</p>
<p>The returned resource object has action methods which provide high-level behaviors without
the need to interact with the low level <a href="#!angular.service.$xhr"><code>$xhr</code></a> service or
raw XMLHttpRequest.</p></div>
<h2>Dependencies</h2>
<ul class="dependencies"><li>$xhr.cache</li>
</ul>
<h2>Usage</h2>
<div class="usage"><div ng:non-bindable=""><pre class="brush: js; html-script: true;">$resource(url[, paramDefaults][, actions]);</pre>
</div>
<h3>Parameters</h3>
<ul class="parameters"><li><code ng:non-bindable="">url – {string} – </code>
<p>A parameterized URL template with parameters prefixed by <code>:</code> as in
<code>/user/:username</code>.</p></li>
<li><code ng:non-bindable="">paramDefaults<i>(optional)</i> – {Object} – </code>
<p>Default values for <code>url</code> parameters. These can be overridden in
<code>actions</code> methods.</p>
<p>Each key value in the parameter object is first bound to url template if present and then any
excess keys are appended to the url search query after the <code>?</code>.</p>
<p>Given a template <code>/path/:verb</code> and parameter <code>{verb:'greet', salutation:'Hello'}</code> results in
URL <code>/path/greet?salutation=Hello</code>.</p>
<p>If the parameter value is prefixed with <code>@</code> then the value of that parameter is extracted from
the data object (useful for non-GET operations).</p></li>
<li><code ng:non-bindable="">actions<i>(optional)</i> – {Object.<Object>} – </code>
<p>Hash with declaration of custom action that should extend the
default set of resource actions. The declaration should be created in the following format:</p>
<pre><code>{action1: {method:?, params:?, isArray:?, verifyCache:?},
action2: {method:?, params:?, isArray:?, verifyCache:?},
...}
</code></pre>
<p>Where:</p>
<ul>
<li><code>action</code> – {string} – The name of action. This name becomes the name of the method on your
resource object.</li>
<li><code>method</code> – {string} – HTTP request method. Valid methods are: <code>GET</code>, <code>POST</code>, <code>PUT</code>, <code>DELETE</code>,
and <code>JSON</code> (also known as JSONP).</li>
<li><code>params</code> – {object=} – Optional set of pre-bound parameters for this action.</li>
<li>isArray – {boolean=} – If true then the returned object for this action is an array, see
<code>returns</code> section.</li>
<li>verifyCache – {boolean=} – If true then whenever cache hit occurs, the object is returned and
an async request will be made to the server and the resources as well as the cache will be
updated when the response is received.</li>
</ul></li>
</ul>
<h3>Returns</h3>
<div class="returns"><code ng:non-bindable="">{Object}</code>
– <p>A resource "class" object with methods for the default set of resource actions
optionally extended with custom <code>actions</code>. The default set contains these actions:</p>
<pre><code>{ 'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'} };
</code></pre>
<p>Calling these methods invoke an <a href="#!angular.service.$xhr"><code>angular.service.$xhr</code></a> with the specified http method,
destination and parameters. When the data is returned from the server then the object is an
instance of the resource class <code>save</code>, <code>remove</code> and <code>delete</code> actions are available on it as
methods with the <code>$</code> prefix. This allows you to easily perform CRUD operations (create, read,
update, delete) on server-side data like this:</p><div ng:non-bindable><pre class="brush: js; html-script: true;">
var User = $resource('/user/:userId', {userId:'@id'});
var user = User.get({userId:123}, function(){
user.abc = true;
user.$save();
});
</pre></div><p>It is important to realize that invoking a $resource object method immediately returns an
empty reference (object or array depending on <code>isArray</code>). Once the data is returned from the
server the existing reference is populated with the actual data. This is a useful trick since
usually the resource is assigned to a model which is then rendered by the view. Having an empty
object results in no rendering, once the data arrives from the server then the object is
populated with the data and the view automatically re-renders itself showing the new data. This
means that in most case one never has to write a callback function for the action methods.</p>
<p>The action methods on the class object or instance object can be invoked with the following
parameters:</p>
<ul>
<li>HTTP GET "class" actions: <code>Resource.action([parameters], [callback])</code></li>
<li>non-GET "class" actions: <code>Resource.action(postData, [parameters], [callback])</code></li>
<li>non-GET instance actions: <code>instance.$action([parameters], [callback])</code></li>
</ul></div>
</div>
<h2>Example</h2>
<div class="example"><h3>Credit card resource</h3><div ng:non-bindable><pre class="brush: js; html-script: true;">
// Define CreditCard class
var CreditCard = $resource('/user/:userId/card/:cardId',
{userId:123, cardId:'@id'}, {
charge: {method:'POST', params:{charge:true}}
});
// We can retrieve a collection from the server
var cards = CreditCard.query();
// GET: /user/123/card
// server returns: [ {id:456, number:'1234', name:'Smith'} ];
var card = cards[0];
// each item is an instance of CreditCard
expect(card instanceof CreditCard).toEqual(true);
card.name = "J. Smith";
// non GET methods are mapped onto the instances
card.$save();
// POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'}
// server returns: {id:456, number:'1234', name: 'J. Smith'};
// our custom method is mapped as well.
card.$charge({amount:9.99});
// POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'}
// server returns: {id:456, number:'1234', name: 'J. Smith'};
// we can create an instance as well
var newCard = new CreditCard({number:'0123'});
newCard.name = "Mike Smith";
newCard.$save();
// POST: /user/123/card {number:'0123', name:'Mike Smith'}
// server returns: {id:789, number:'01234', name: 'Mike Smith'};
expect(newCard.id).toEqual(789);
</pre></div><p>The object returned from this function execution is a resource "class" which has "static" method
for each action in the definition.</p>
<p>Calling these methods invoke <code>$xhr</code> on the <code>url</code> template with the given <code>method</code> and <code>params</code>.
When the data is returned from the server then the object is an instance of the resource type and
all of the non-GET methods are available with <code>$</code> prefix. This allows you to easily support CRUD
operations (create, read, update, delete) on server-side data.</p><div ng:non-bindable><pre class="brush: js; html-script: true;">
var User = $resource('/user/:userId', {userId:'@id'});
var user = User.get({userId:123}, function(){
user.abc = true;
user.$save();
});
</pre></div><pre><code>It's worth noting that the callback for `get`, `query` and other method gets passed in the
response that came from the server, so one could rewrite the above example as:
</code></pre><div ng:non-bindable><pre class="brush: js; html-script: true;">
var User = $resource('/user/:userId', {userId:'@id'});
User.get({userId:123}, function(u){
u.abc = true;
u.$save();
});
</pre></div><h3>Buzz client</h3>
<p>Let's look at what a buzz client created with the <code>$resource</code> service looks like:</p><doc:example>
<pre class="doc-source">
<script>
function BuzzController($resource) {
this.Activity = $resource(
'https://www.googleapis.com/buzz/v1/activities/:userId/:visibility/:activityId/:comments',
{alt:'json', callback:'JSON_CALLBACK'},
{get:{method:'JSON', params:{visibility:'@self'}}, replies: {method:'JSON', params:{visibility:'@self', comments:'@comments'}}}
);
}
BuzzController.prototype = {
fetch: function() {
this.activities = this.Activity.get({userId:this.userId});
},
expandReplies: function(activity) {
activity.replies = this.Activity.replies({userId:this.userId, activityId:activity.id});
}
};
BuzzController.$inject = ['$resource'];
</script>
<div ng:controller="BuzzController">
<input name="userId" value="googlebuzz"/>
<button ng:click="fetch()">fetch</button>
<hr/>
<div ng:repeat="item in activities.data.items">
<h1 style="font-size: 15px;">
<img src="{{item.actor.thumbnailUrl}}" style="max-height:30px;max-width:30px;"/>
<a href="{{item.actor.profileUrl}}">{{item.actor.name}}</a>
<a href ng:click="expandReplies(item)" style="float: right;">Expand replies: {{item.links.replies[0].count}}</a>
</h1>
{{item.object.content | html}}
<div ng:repeat="reply in item.replies.data.items" style="margin-left: 20px;">
<img src="{{reply.actor.thumbnailUrl}}" style="max-height:30px;max-width:30px;"/>
<a href="{{reply.actor.profileUrl}}">{{reply.actor.name}}</a>: {{reply.content | html}}
</div>
</div>
</div>
</pre>
<pre class="doc-scenario">
</pre>
</doc:example></div>
</div>