AngularJS–Part 9, Values and constants

Introduction

This is a series of posts about AngularJS and our experiences with it while migrating the client of a complex enterprise application from Silverlight to HTML5/CSS/JavaScript using AngularJS as a framework. Since the migration is a very ambitious undertaken I want to try to chop the overall problem space in much smaller pieces that can be swallowed and digested much more easily by any member of my team. So far I have published the following posts in this series

Sometimes we need some data that is globally available but at the same time we do not want to pollute the global (window) namespace with the definition for this data. Angular provides us the value and constant services which can do exactly this. Values and constants declared in this way can be injected into any controller or service like any other dependency (e.g. $scope, $http, etc.).

Values

In our application we frequently need access to different properties of the currently logged in user. This could be things like the full name of the user, it’s role and so on. Typically we would load this data after the user has successfully logged into the system and keep this data around as long as the user remains logged in.

We can define any string, number, date-time, array or object as a value. We can even register a function as a value. To e.g. define a string value as a value service we use this code

image

On line 1 I define my Angular application (module). On line 3 I register a value appTitle with the value “My Angular Application”. If we now want to use this value say in a controller TestCtrl we can do so

image

Angular interferes which service to inject by looking at the name of the parameter. Thus our function parameter has to be named the same way as the registered value.

We will discuss dependency injection (DI) and how it is realized in Angular in a future post.

As mentioned above, we can also e.g. register an object as value service.

image

The above code defines and initializes a value service called user and assigns it an object with some default values. We can now load the true values e.g. after a successful login of the user. I just quickly put together some pseudo code for this scenario (do not use this in production Winking smile)

image

The above code is assuming that the user entered a user name and a password, selected the local and the connection (in our application a user can connect to different sites which we distinguish via unique connection names). The user then clicks on a login button which triggers the execution of the above login function. The data the user has entered is posted to the backend and assuming the user can be authenticated the server will respond with a success status and send back the user data.

Note: Make sure that you never overwrite the value service/object as a whole otherwise your assignment is lost. Always reassign the property values of the value object. The following assignment is wrong and does not lead to the expected behavior

image

even if the layout of the response matches the user value object exactly. We have to do a mapping property by property, i.e.

image

Constants

The difference between a value and a constant service is that the former can only be injected (and thus be used) in a service or a controller while the latter can also be injected into a module configuration function.. (I will discuss the module configuration function in a future post).

Summary

Angular value and constant services are an ideal way to provide application wide access to shared data without having to pollute the global namespace. They can be injected similar to any other service into our controllers and services. The only real difference between a value and a constant is that the latter can be injected into  a module configuration function while the former cannot.

Related Articles:

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

About Gabriel Schenker

Gabriel N. Schenker started his career as a physicist. Following his passion and interest in stars and the universe he chose to write his Ph.D. thesis in astrophysics. Soon after this he dedicated all his time to his second passion, writing and architecting software. Gabriel has since been working for over 12 years as an independent consultant, trainer, and mentor mainly on the .NET platform. He is currently working as chief software architect in a mid-size US company based in Austin TX providing software and services to the pharmaceutical industry as well as to many well-known hospitals and universities throughout the US and in many other countries around the world. Gabriel is passionate about software development and tries to make the life of developers easier by providing guidelines and frameworks to reduce friction in the software development process. Gabriel is married and father of four children and during his spare time likes hiking in the mountains, cooking and reading.
This entry was posted in AngularJS, introduction. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • tamizhvendan

    Hi,

    Nice post !

    By the way, can you specify why “user = response” will not work ?

    • Zack

      It would, but if the response contained fewer properties than the user object has (say the user object has a property user.date = Date.now by default), the user object would loose the missing properties.

  • 世强 汤

    Nice post !

  • hmathews

    Not works :(

    DECLARING VALUE:

    angular.module(‘frontSrcApp’, ['ffa.ui.picker', 'ffa.ui.gnameindexer', 'ngRoute', 'ngResource', 'ngSanitize', 'angularMoment', 'timeRelative', 'ui.tinymce', 'restangular', 'pascalprecht.translate', 'ui.bootstrap', 'kalitte.services'])

    .config([‘$routeProvider’, ‘RestangularProvider’, ‘$translateProvider’, ‘appBusyProvider’, function ($routeProvider, RestangularProvider, $translateProvider, appBusyProvider) {

    app.value(‘saludo’, ‘hola desde config’);

    USING VALUE:

    angular.module(‘frontSrcApp’)

    .controller(‘BuildingManagementCtrl’, [‘MultiLangHelperSrv’, ‘ServicesSrv’, ‘$scope’, ‘$rootScope’, ‘ErrorSrv’, ‘$log’, ‘$translate’, function (MultiLangHelperSrv, ServicesSrv, $scope, $rootScope, ErrorSrv, $log, $translate, saludo) {

    alert(saludo);

    • hmathews

      solved by using $provide inside config and method constant:

      $provide.constant(‘saludo’, ‘hola desde config’);

      thx anyway!