Skip to content

AngularFundamentalsServices

Illegitimis edited this page Jun 8, 2017 · 3 revisions

Creating and Using Angular Services

  • an object that is used to encapsulate some sort of business logic, or just does some sort of work. just a worker object
  • often stateless, although it isn't unusual for a service to cache data that is accessed frequently.
  • It is not accessed over the wire, although it may be used to perform operations that do go over-the-wire, such as making AJAX calls
  • Just an object that has methods and properties on it that we can reuse
  • Registering a service with Angular is simple, and, once registered, it now becomes part of the Angular world and it can be used like any other Angular service. It can now be easily injected into your controllers and directives and filters and even into other services.
  • $scope param in controller is a service! do not use dollar sign for your own services.
  • What you pass into the factory method is the name of the service, and then a function that returns the object that will become that service.

Built-in

$http

good for non-restful calls, raw, regardless of endpoint type

EventData.js

eventsApp.factory('eventData', function($http) {
    return {
        getEvent: function (cb) {
            $http({method:'GET', url:'/data/event/1'}).
               success(function(data, status, headers, config) {
                   cb(data);
               }).
               error(function(data, status, headers, config) {
                   $log.warn (data, status, headers(), config);
               });
        }        
    };
});

Controller calls eventData.getEvent(function(event) {$scope.event=event;});

web-server.js with node server

var events = require('./eventsController');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.get('/data/event/:id', events.get);
app.post('/data/event/:id', events.save);

eventController.js

    var fs = require('fs');
     
    module.exports.get = function(req, res) {
        var event = fs.readFileSync('app/data/event/' + req.params.id + '.json', 'utf8');
        res.setHeader('Content-Type', 'application/json');
        res.send(event);
    };
     
    module.exports.save = function(req, res) {
       var event = req.body;
       fs.writeFileSync('app/data/event/' + req.params.id + '.json', JSON.stringify(event));
       res.send(event);
    }

$promise

.\app\js\controllers\EditEventController.js

'use strict';

eventsApp.controller('EditEventController',
    function EditEventController($scope, eventData) {

        $scope.event = {};

        $scope.saveEvent = function(event, newEventForm) {
            if(newEventForm.$valid) {
                eventData.save(event)
                    .$promise
                    .then(function(response) { console.log('success', response)})
                    .catch(function(response) { console.log('failure', response)});
            }
        };

        $scope.cancelEvent = function() {
          window.location = '/EventDetails.html';
        }

    }
);

$resource

good for restful web apis include reference to angular-resource.js. add to app.js the module .\app\js\services\EventData.js

eventsApp.factory('eventData', function($resource) {
    var resource = $resource('/data/event/:id', {id:'@id'}, {"getAll": {method: "GET", isArray: true, params: {something: "foo"}}});
    return {
        getEvent: function(eventId) {
            return resource.get({id:eventId});
        },
        save: function(event) {
            event.id = 999;
            return resource.save(event);
        },
        getAllEvents: function() {
            return resource.query();
        }
    };
});

.\app\js\services\userResource.js

'use strict';

eventsApp.factory('userResource', ['$resource', function ($resource) {
    var service = $resource('/data/user/:userName', {userName:'@userName'}, { });

    service.queryAll = function (callback) {
        return service.query({}, callback)
    };

    return service;
}]);

<<

Clone this wiki locally