AngularJS: Services, Factories and Providers

Angular concepts underlines

Services

Syntax: module.service( ‘serviceName’, function );

Result: When declaring serviceName as an injectable argument you will be provided the actual function reference passed to module.service.

Usage: Could be useful for sharing utility functions that are useful to invoke by simply appending () to the injected function reference. Could also be run with injectedArg.call( this ) or similar.

Factories

Syntax: module.factory( ‘factoryName’, function );

Result: When declaring factoryName as an injectable argument you will be provided the value that is returned by invoking the function reference passed to module.factory.

Usage: Could be useful for returning a ‘class’ function that can then be new’ed to create instances.

Providers

Syntax: module.provider( ‘providerName’, function );

Result: When declaring providerName as an injectable argument you will be provided the value that is returned by invoking the $get method of the function reference passed to module.provider.

Usage: Could be useful for returning a ‘class’ function that can then be new’ed to create instances but that requires some sort of configuration before being injected. Perhaps useful for classes that are reusable across projects? Still kind of hazy on this one.

 

Live Example

Source

 

HTTP/2 Server Push

Angular e React tools

HTTP/2 allows a server to pre-emptively send (or “push”) responses (along with corresponding “promised” requests) to a client in association with a previous client-initiated request. This can be useful when the server knows the client will need to have those responses available in order to fully process the response to the original request.

Source

Standard JavaScript errors

Error Handling

  • <EvalError> : thrown when a call to eval() fails.
  • <SyntaxError> : thrown in response to improper JavaScript language syntax.
  • <RangeError> : thrown when a value is not within an expected range
  • <ReferenceError> : thrown when using undefined variables
  • <TypeError> : thrown when passing arguments of the wrong type
  • <URIError> : thrown when a global URI handling function is misused.

Source.

Concepts of imperative, procedural and declarative programming

Are all programming languages imperatives?

In computer science, imperative programming is a programming paradigm that uses statements that change a program’s state. In much the same way that the imperative mood in natural languages expresses commands, an imperative program consists of commands for the computer to perform. Imperative programming focuses on describing how a program operates.

Procedural programming is a type of imperative programming in which the program is built from one or more procedures (also termed subroutines or functions). The terms are often used as synonyms, but the use of procedures has a dramatic effect on how imperative programs appear and how they are constructed. Heavily-procedural programming, in which state changes are localized to procedures or restricted to explicit arguments and returns from procedures, is termed structured programming. From the 1960s onwards, structured programming and modular programming in general have been promoted as techniques to improve the maintainability and overall quality of imperative programs. Object-oriented programming extends this approach.[1]

Procedural programming could be considered a step towards declarative programming. A programmer can often tell, simply by looking at the names, arguments, and return types of procedures (and related comments), what a particular procedure is supposed to do, without necessarily looking at the details of how it achieves its result. At the same time, a complete program is still imperative since it fixes the statements to be executed and their order of execution to a large extent.

Contrasting with imperative and procedural programming is declarative programming, a non-imperative programming style in which programs describe their desired results without explicitly listing commands or steps that must be performed.

The hardware implementation of almost all computers is imperative.[note 1] Nearly all computer hardware is designed to execute machine code, which is native to the computer, written in the imperative style.

From this low-level perspective, the program state is defined by the contents of memory, and the statements are instructions in the native machine language of the computer. Higher-level imperative languages use variables and more complex statements, but still follow the same paradigm.

The earliest imperative languages were the machine languages of the original computers. In these languages, instructions were very simple, which made hardware implementation easier, but hindered the creation of complex programs. FORTRAN, developed by John Backus at International Business Machines (IBM) starting in 1954, was the first major programming language to remove the obstacles presented by machine code in the creation of complex programs. FORTRAN was a compiled language that allowed named variables, complex expressions, subprograms, and many other features now common in imperative languages.

From this Source.

 

AngularJS Services vs. Factories

Um .service ou .factory no AngularJS são métodos no nosso módulo principal (app), que recebem um nome e uma função que o definem.

Uma vez definido, podemos injetar e usar .service ou .factory  em outros componentes. Basta colocá-los como dependência em Directives, Controllers e Filters.

AngularJS funções contrutoras e ‘class-like’

Um .service é uma função construtora, enquanto um .factory é somente uma função que é chamada. Por este motivo precisamos retornar um objeto.

Como regra geral, nós usamos .factory para funções “class-like”, nas quais você pode adicionar propriedades/atributos e retornar para um controller.

Por outro lado, podemos usar .service para compartilhar funções utilitárias/construtoras.

Service

  • Função Construtora, Utilitária
  • Retorna uma instância dele mesmo
  • Usa this ou vm = this
  • new ServiceName()

Factory

  • Função Class-like
  • Retorna um novo Objeto
  • Pode adicionar propriedades e atributos

Fontes aqui e aqui.

JavaScript: Prototype-based programming language

Object Oriented programming language

Prototypal inheritance in JavaScript is described by Douglas Crockford as: you make prototype objects, and then … make new instances. Objects are mutable in JavaScript, so we can augment the new instances, giving them new fields and methods. These can then act as prototypes for even newer objects. We don’t need classes to make lots of similar objects… Objects inherit from objects. What could be more object oriented than that?.[1]

Angular Concepts

Concept Description
Template HTML with additional markup
Directives extend HTML with custom attributes and elements
Model the data shown to the user in the view and with which the user interacts
Scope context where the model is stored so that controllers, directives and expressions can access it
Expressions access variables and functions from the scope
Compiler parses the template and instantiates directives and expressions
Filter formats the value of an expression for display to the user
View what the user sees (the DOM)
Data Binding sync data between the model and the view
Controller the business logic behind views
Dependency Injection Creates and wires objects and functions
Injector dependency injection container
Module a container for the different parts of an app including controllers, services, filters, directives which configures the Injector
Service reusable business logic independent of views

Source

AngularJS Tutorial Overview by Todd Motto

The View consists of the presentation layer, the ViewModel contains the presentation logic and the Model contains our business logic and data.

Model changes propagate to the View, and View changes are instantly reflected back to the Model.

Angular use plain old JavaScript Objects for synchronising Model and View data-bindings. Angular parses back to JSON and communicates best with a REST endpoint. This approach makes building front-end applications seamless as all the application state is held on the browser, not delivered in pieces from a server and state becomes lost.

The way we bind these values is through Angular expressions, which take shape as handlebar templates.

 

Injectors and Services

An injection is the passing of a dependency to a dependent Object, these dependencies are often referred to as Services.

 

Managing state and HTTP

AngularJS manage state entirely in the browser and communicate changes when we want them to via Ajax (HTTP) using GET, POST, PUT and DELETE methods, typically talking to a REST endpoint backend.

 

Modules

Every application in Angular is created using modules. A module can have dependencies of other modules, or be a single module all by itself. These modules act as containers for different sections of an application, making code more reusable and testable. To create a module, we hit the global angular Object, the framework’s namespace, and use the module method.

Setters:

var app = angular.module('app', [moduleDependencies, n...]);

Getters:

angular.module('app');

HTML bootstrapping:

<html ng-app="app">
  <head></head>
  <body></body>
</html>

If we’re loading our JavaScript files asynchronously then we need to manually bootstrap the application using angular.bootstrap(document.documentElement, ['app']);.

 

$scope

Think of $scope as an automated bridge between JavaScript and the DOM itself which holds our synchronised data. This allows us to template easier using handlebars syntax inside the HTML we love, and Angular will render out the associated $scope values. This creates a binding between JavaScript and the DOM, the $scope Object is really a glorified ViewModel.

We only use $scope inside Controllers, where we bind data from the Controller to the View:

$scope.someValue = 'Hello';

We can bind any values to $scope that exist as types in JavaScript. This is how we transfer data from a service which talks to the server and pass it on to our View.

 

$rootScope

It is the very top level$scope Object from which all further scopes are created.

 

Controllers

An Angular Controller allows us to interact with a View and Model, it’s the place where presentational logic can take place to keep the UI bindings in sync with the Model. A Controller’s purpose is to drive Model and View changes, in Angular it’s a meeting place between our business logic and our presentational logic.

function MainCtrl () { } 

angular .module('app', []) 
.controller('MainCtrl', MainCtrl);

Once a View is updated, the Controller logic is also updated and can be passed back to the server using a Service.

 

Methods


function MainCtrl ($scope) {
$scope.items = [{
name: 'Scuba Diving Kit',
id: 7297510
},{
name: 'Snorkel',
id: 0278916
},{
name: 'Wet Suit',
id: 2389017
},{
name: 'Beach Towel',
id: 1000983
}];
}

angular
.module('app')
.controller('MainCtrl', MainCtrl);

 

controllerAs

The first change for controllerAs is dropping $scope references for data bound inside the Controller and using this instead.

function MainCtrl () {
  this.items = [{
    name: 'Scuba Diving Kit',
    id: 7297510
  },{
    name: 'Snorkel',
    id: 0278916
  },{
    name: 'Wet Suit',
    id: 2389017
  },{
    name: 'Beach Towel',
    id: 1000983
  }];
}

angular
  .module('app')
  .controller('MainCtrl', MainCtrl);

The next change is adding the as part to where we instantiate the Controller in the DOM, let’s use MainCtrl as main to create a main variable.

<div ng-controller="MainCtrl as main">
  <ul>
      <li ng-repeat="item in main.items">
          {{ item.name }}
      </li>
  </ul>
</div>

 

Services and Factories

Services are where we would create to hold our application’s Model data and business logic such as talking to the server over HTTP. It’s important to remember that all Services are application singletons, there is only one instance of a Service per injector. By convention all custom Services should follow Pascal Case.

 

Service Method

A service is just aconstructor Object that gets called with the new keyword, which means we’ll be using the this keyword to bind our logic to the Service. The service creates a singleton Object created by a service factory.

 

Factory Method

Factory methods return an Object or a Function, which means we can make usage of closures as well as returning a host Object to bind methods to. We can create private and public scope. All Factories become a Service, to we should refer to them as a Service not the pattern they are named after.

We’ll recreate the UserService above using the factory method for comparison.

function UserService () {
  var UserService = {};
  function greeting (name) {
    return 'Hello there ' + name;
  }
  UserService.sayHello = function (name) {
    return greeting(name);
  };
  return UserService;
}

angular
  .module('app')
  .factory('UserService', UserService);

 

Templates

Expressions

<div ng-controller="MainCtrl as main">
  {{ main.items.length }}
  <ul> 
   <li ng-repeat="item in main.items" ng-click="main.removeFromStock(item, $index)"> {{ item.name }} 
   </li> 
  </ul>
</div>

As we create methods, the this value may change depending on how we use it due to the function’s execution context. Create a reference to the Controller using a variable var vm = this; (“vm” = “ViewModel”). This way we don’t lose any lexical this references and avoid using Function.prototype.bind to keep changing context, or Angular’s own angular.bind.

function MainCtrl () {
  var vm = this;
  vm.removeFromStock = function (item, index) {
    vm.items.splice(index, 1);
  };
}

 

Directives

A Directive can be anything, it can either provide powerful logic to an existing specific element, or be an element itself and provide an injected template with powerful logic inside. The idea behind them is around extending HTML’s capabilities, as if it were made for building compelling data-driven web applications.

 

ng-repeat

<ul>
  <li ng-repeat="item in main.items">
    {{ item }}
  </li>
</ul>

ng-model

<input type="text" ng-model="main.message">
<p>Message: {{ main.message }}</p>

ng-click

<button ng-click="count = count + 1" ng-init="count=0">
  Increment
</button>
<span>
  count: {{count}}
</span>