angular/angular.js — pull request #7308 by yohairosen (2014-04-30 09:05:53+00:00)
Title: Extending resources

A suggested solution for #4565

Request Type: feature

How to reproduce:
- **Array type action bug**: create a resource with a custom action from type array, call that action on an instance of your custom resource. Exception is thrown.
- **Extending resource feature**: You want the response of your action call to become a part of your resource instance. There is currently no straight forward way of doing this.

Component(s): ngResource

Impact: small

Complexity: small

This issue is related to:

When calling a Resource instance's ```GET``` actions such as ```$get``` and ```$query``` but mostly custom ones, it is sometimes needed to be able to extend the resource with the response data e.g:

```javascript
entity.$children()
.then(function(){
console.log(entity.children) //undefined
});
//the response did not become a part of the resource
```
Automatically setting the response on the resource with the property name is a bad idea since it can lead to unexpected overrides (the resource might have had a property named children) and generally it should be up to the user to decide whether to extend or not and how.

My approach involves leveraging the Resource's interceptor to achieve a both flexible and clean way to extend instances. By calling the interceptor's response function with the instance as it's context (this) it is possible to reference it and set the desired properties:

```javascript
$resource('[...]/entity/:id', {}, {
'children': {
method: 'GET',
url:'[...]/entity/:id/children',
params:{id:'@id'},
isArray:true,
interceptor:{
response: function(response){
var data = response.data;
this.children = data; //"this" references the entity resource
return data;
}
}
}
});
```