Resources in AngularJS

$resource

It’s a factory used to create resource objects to be able to interact with RESTful services data sources stored in local server or other domains.

This service is part of ngResource module, which must be declared in the page:

<script src="angular-resource.js">
 

This module provides support to interact with those services.

The following code shows three factories being registered on the module. For this, two parameters are needed: a name and a function that returns a registered provider instance, a $resource in this case.

'use strict';

/**
 * 
 * @name myLibraryApp.services
 * @description
 * # myLibraryApp.services
 *
 * Main service module of the application.
 */
angular.module('myLibraryApp.services', [])
	.factory('Subjects', function( $resource ) {
		return $resource('http://localhost:3000/subjects/:id', { id : '@_id' }, {
			'update' : { method : 'PUT' }
		});
	})
	.factory('Documents', function( $resource ) {
		return $resource('http://localhost:3000/documents/:id', { id : '@_id' }, {
			'query' : { method : 'GET', params : { subject : '@subject' }, isArray : true },
			'update' : { method : 'PUT' }
		});
	})
	.factory('DocumentsCount', function( $resource ) {
		return $resource('http://localhost:3000/documents/count');
	});
 

The factory function returns a $resource object with some elements. In our case, all three resources have different elements. Explanation:

The first $resource has three arguments (this applies for every $resource):

  1. URL: 'http://localhost:3000/subjects/:id'. Note that the parameter :id is included because we want to use it to do some actions with a specific subject having this id: update, delete or select. The parameters are defined in the URL by prefixing : to the name.
  2. Parameter defaults: { id : '@_id' }. In our case, it will store a default value on the id parameter. This value will be extracted from the data object property. Also, we can pass fixed values.
  3. Custom CRUD action methods: { 'update' : { method : 'PUT' } }. We can define here the CRUD action specifications. There are many elements to be implemented, but we will use only method.
.factory('Subjects', function( $resource ) {
	return $resource('http://localhost:3000/subjects/:id', { id : '@_id' }, {
		'update' : { method : 'PUT' }
	});
})
 

The name 'update' will be used later in the application, when subject details are modified by sending data on the subjects’ list page.

...

		$scope.updateSubject = function(subject) {
			// Start timing now
			console.time('SubjectsListController.updateSubject.job.timespan');

			// update document on MongoDB
			delete subject.__v;
			delete subject.created_at;

			subject.$update()
				.then(function () {
					// refresh the page
					$state.go($state.current, {}, { reload: true });
				});

			// Stop timer.
			console.timeEnd('SubjectsListController.updateSubject.job.timespan');
		};

...
 

The second factory, like the first case, this one has the same structure, but one more action: 'query'.

.factory('Documents', function( $resource ) {
	return $resource('http://localhost:3000/documents/:id', { id : '@_id' }, {
		'query' : { method : 'GET', params : { subject : '@subject' }, isArray : true },
		'update' : { method : 'PUT' }
	});
})
 

As you can see next, in the documentsController.js file, we pass the subject parameter value : $stateParams.subject.

...

// GET all subjects in a JSON array
$scope.documentsList = Documents.query({}, { subject : $stateParams.subject });

...
 

You probably noted the isArray : true element on the ‘query’ action. This is because we will receive from the server the book’s list as an array.

In the third case, no other parameters are passed, only the URL pointing to a data source located in the same server. This URL could be the path of a server located in other domain. If so, this one must have granted access permissions to accept requests from the client’s application. See this article presenting CORS.

.factory('DocumentsCount', function( $resource ) {
	return $resource('http://localhost:3000/documents/count');
})
 

Conclusion

$resource service is a good tool to interact with data sources using RESTful services. ngResource module must be present in the page to give functionality to this service.

Related Links

https://docs.angularjs.org/api/ngResource

https://docs.angularjs.org/api/ngResource/service/$resource

Leave a comment