Simple example of calling DreamFactory with Angular's $resource

Angular’s $resource is a simple construct for calling any REST API. Here are a few simple examples of using $resource with DreamFactory.

Let’s say we create a table ‘foo’ in DreamFactory (or an external SQL or NoSQL database that DreamFactory connects to) and we want to post a record to this table. We can create a simple Angular service (or factory), like so:

// services.js

var baseUrl = 'https://dsp-yourdsp.cloud.dreamfactory.com'; // your dsp
var appName = 'someApp'; // app name is your api key

angular.module('someApp.services', ['ngResource'])

    .service('AddFooService', ['$resource', function ($resource) {
        return $resource(baseUrl + '/rest/db/foo',
            { appName: appName },
            { save: { method: 'POST' }
        });
    }])

Now we can inject this simple service into any of our Angular controllers, like this:

 .controller('AddFooCtrl', ['$scope', '$location', 'AddFooService', function($scope, $location, AddFooService) {

        $scope.addFoo = function () {
             AddFooService.save(($scope.foo), function () {
                $location.url('/all-foos');
            });
        };
    }])

Other CRUD operations are similar. Say we want to GET some records from the ‘foo’ table with a filter, like only records belonging to the currently logged in user (note in this example we’re using the GetCurrentUser() method of the DreamFactory User Management module for Angular to get the user ID of the authenticated user). We can easily specify an Angular service to do this.

.service('GetSomeFoosService', ['$resource', function ($resource) {
        return $resource(baseUrl + '/rest/db/foo',
            { appName: appName, fields: '@fields', filter: '@filter' },
            { query: { method: 'GET' , isArray: false }
            });
    }])

Now we can call this service from a controller to fetch the records belonging to the logged in user.

.controller('GetSomeFoosCtrl', ['$scope', '$location', 'UserDataService', 'GetSomeFoosService', function($scope, $location, UserDataService, GetSomeFoosService) {

    $scope.params = {
        // define fields in the foo table you to fetch (* will get all fields)
        fields: 'name' + ',' + 'description', 
        
       // only get records in the foo table for the logged in user
       filter: 'userId=' + UserDataService.getCurrentUser().id   
    };

    $scope.foos = GetSomeFoosService.query($scope.params);

}])