Mastering Web Application

(Rick Simeone) #1
Chapter 1
},
// other methods go here
};
}
};
});

Firstly a provider is a function that must return an object containing the $get
property. The mentioned $get property is a factory function, that when invoked
should return a service instance. We can think of providers as objects that embed
factory functions in their $get property.


Next, an object returned from a provider function can have additional methods and
properties. Those are exposed, so it is possible to set configuration options before the
$get (factory) method gets invoked. Indeed, we can still set the maxLen configuration
property, but we are no longer obliged to do so. Furthermore, it is possible to have
more complex configuration logic, as our services can expose configuration methods
and not only simple configuration values.


Modules lifecycle

In the previous paragraphs, we could see that AngularJS supports various recipes
for object's creation. A provider is a special kind of recipe, since it can be further
configured before it produces any object instances. To effectively support providers,
AngularJS splits module's lifecycle into two phases, which are as follows:



  • The configuration phase: It is the phase where all the recipes
    are collected and configured

  • The run phase: It is the phase where we can execute any
    post-instantiation logic


The configuration phase


Providers can be configured only during the configuration (first) phase. Surely, it
doesn't make sense to change a recipe after objects are baked, right? Providers can
be configured as shown in the following code:


myMod.config(function(notificationsServiceProvider){
notificationsServiceProvider.setMaxLen(5);
});

The important thing to notice here is a dependency on the
notificationsServiceProvider objects with the Provider suffix
representing the recipes that are ready to be executed. The configuration
phase allows us to do the last-moment tweaks to the objects' creation formula.

Free download pdf