AngularJS $http and logger Circular Dependency

Error

[$injector:cdep] Circular dependency found: $rootScope <- $http <- logger <- $exceptionHandler <- $rootScope <- $location <- routehelper

TLDR:

If you are looking for RequireJS's easy way to late-bind a dependency, here's how you do it in AngularJS.

var $http = angular.injector(['ng']).get('$http');

Story

I imagine this could be a fairly common scenario.

You implemented AngularJS, with a logger service.

 angular
     .module('blocks.logger')
     .factory('logger', logger);

 logger.$inject = ['$log'];
 function logger($log) {
        var service = {
            error   : error,
            log     : $log.log
        };
        return service;

        /////////////////////

        function error(message, data, title) {
            $log.error('Error: ' + message, data);
        }
}

You want to try to catch errors and log it back to your webservice
So add a REST call.

logger.$inject = ['$log', '$http'];
function logger($log, $http) {
    // snip.

    function error(message, data) {
        $log.error('Error: ' + message, data);

        var request = {
            method : 'POST',
            url: _spPageContextInfo.webServerRelativeUrl + '/_layouts/MyLogService.svc/LogMessage',
            data: {
                'log': message,
                'event': 'error',
                'meta': angular.toJson(data)
            },
            dataType: "json",
            headers: {
                "Content-Type": "application/json; charset=utf-8"
            }
        };
        $http(request);           
    }
}


Error!

[$injector:cdep] Circular dependency found: $rootScope <- $http <- logger <- $exceptionHandler <- $rootScope <- $location <- routehelper

I actually quite like this error.  It's telling me the dependency tree starting from routehelper and looping around to $rootScope

Bingle will tell you to re-architect your solution so you have proper separation of concerns.  But to be honest, I just want to log an error…

So here's how you do it.

var ng = angular.injector(['ng']);
var $http = ng.get('$http');

Final Code Summary

logger.$inject = ['$log'];
function logger($log) {
    // snip.

    function error(message, data) {
        $log.error('Error: ' + message, data);
        
        // inject $http here.
        var $http = angular.injector(['ng']).get('$http');
        if (!$http) return;
            var request = {
                method : 'POST',
                url: _spPageContextInfo.webServerRelativeUrl + '/_layouts/MyLogService.svc/LogMessage',
                data: {
                    'log': message,
                    'event': 'error',
                    'meta': angular.toJson(data)
                },
                dataType: "json",
                headers: {
                    "Content-Type": "application/json; charset=utf-8"
                }
            };
            $http(request);           
        }
}

AngularJS Extend and Computed Property

This is an Intermediate level discussion on AngularJS Extend, Computed Property in general, and a fairly complicated binding bug that needs some new learning.

 

I came from a KnockoutJS world.  In the KnockoutJS world which I'm familiar with, there is the concept of a Computed Property.

KnockoutJS Computed Property

Because native Javascript objects does not raise OnPropertyChanged events, KnockoutJS wraps properties with an observable wrapper.
A class would look like this:

function PersonViewModel(){
  var self = this;
  
  self.firstName = ko.observable("");
  self.lastName = ko.observable("");
  
  self.fullName = ko.computed(function(){
    return [
      ko.unwrap(self.firstName), 
      ko.unwrap(self.lastName)
    ].join(" ");
  });
}

The developer takes care of the properties firstName and lastName, and KnockoutJS understands when firstName or lastName changes, fullName needs to be re-evaluated.

AngularJS binds Native Javascript Object

In AngularJS, there is no direct concept of a Computed Property, instead, AngularJS watches various binding expressions and automatically re-evaluate expressions.  Since AngularJS binds to native Javascript directly, it employs a dirty checking mechanism.

A native person might look like this:

var person = {
  firstName: "",
  lastName: ""
};

And a View would look like this:

<div>
  First Name: {{ person.firstName }}
  Last Name: {{ person.lastName }}
  Full Name: {{ person.firstName + ' ' + person.lastName }}
</div>

Defining Class for AngularJS

But very quickly, one would find that this gets very unwieldy, and you end up duplicating expressions everywhere in your View.  Duplicated code is never good.  So we need to tidy up the definition of the model a bit more.

function Person(){
  var self = this;
  
  self.firstName = "";
  self.lastName = "";
  
  self.fullName = function(){
    return [self.firstName,self.lastName].join(" ");
  };
}

AngularJS Extend

Such definitions are nice and good, but you will need a way to populate these when you pull your data back from a REST service as JSON.  Luckily, AngularJS provides both angular.extend as well as angular.merge helper methods to get you going quickly. 

If you are familar with jQuery, this is nearly identical to jQuery.extend, it copies the properties from the later objects onto the first one.

var jsonJohn = { firstName: "John", lastName: "Liu" };
var personJohn = angular.extend( new Person(), jsonJohn );

// personJohn should have firstName, lastName 
// and fullName() == 'John Liu'

The updated View is then:

<div>
  First Name: {{ person.firstName }}
  Last Name: {{ person.lastName }}
  Full Name: {{ person.fullName() }}
</div>

Extending Arrays

When you have a collection of people, the code needs to look like this:

var people = [];
var jsonPeople = [
  { firstName: "John", lastName: "Liu" },
  { firstName: "Mark", lastName: "Liu" }
];
people = angular.extend( people, jsonPeople );
<div data-ng-repeat="person in people">
  First Name: {{ person.firstName }}
  Last Name: {{ person.lastName }}
  Full Name: {{ person.fullName() }}
</div>

This looks good initially, except there are a few problems:

  • angular.extend does not know anything about Person class, and fullName is not available
var people = [
  new Person(),
  new Person()
];
var jsonPeople = [
  { firstName: "John", lastName: "Liu" },
  { firstName: "Mark", lastName: "Liu" }
];
people = angular.extend( people, jsonPeople );
  • angular.extend will override people[0] with jsonPeople[0] (not null).  So the result still does not define fullName()

So you need something like this:

var people = [
  new Person() // always show one row by default even if blank
];
var jsonPeople = [
  { firstName: "John", lastName: "Liu" },
  { firstName: "Mark", lastName: "Liu" }
];
var l = jsonPeople.length > people.length ? jsonPeople.length : people.length;
for (var i=0; i < l; i++){
  people[i] = angular.extend( new Person(), people[i], jsonPeople[i] );
  // copy jsonPeople[i] (if not null) onto people[i]
  // copy people[i] onto new Person()
  // store it back on people[i]
}

A subtle bug in copying with extend

The Computed Property doesn't work because the way angular.extend copies references, people[i].fullName is copied to (new Person()).fullName, which means that the (new Person()).fullName is calculating from the previous people[i].fullName, because it uses the 'self' reference.

(let me know if I need to draw a picture)

There are two ways to fix this:

1. We can fix how we extend existing records.

//...
for (var i=0; i < l; i++){
  people[i] = angular.extend( people[i] || new Person(), jsonPeople[i] );
  // OR  people[i] and new Person()
  // so that if there is an existing Person object, it is kept
}

2. We can fix how we define the Person class.  I think this is the better method.

function Person(){
  var self = this;
  
  self.firstName = "";
  self.lastName = "";
  
  Person.prototype.fullName = function(){
    // re-connect 'self' to the current object
    var self = this;
    return [self.firstName,self.lastName].join(" ");
  };
}

This bumps the fullName method to the prototype/supertype, so it is no longer an immediate property defined on the Person object.

Summary

  • Notes on doing computed property in AngularJS
  • How to define a Class for AngularJS
  • How to handle extend and extend an array
  • How to move computed methods to the prototype
  • Plunker http://plnkr.co/edit/HcuxnT3EAVrtz1PyWwXb check out the two Count1 and Count2 computed properties and how they work differently after you clicked 'update'

 

 

 

Notes on KnockoutJS Mapping and ViewModel style guide

I wanted to write down some of the better practices I've settled with since using KnockoutJS for nearly two years now.  A lot of these has to do with just avoiding errors that I see later on, as well as working with the peculiarities of the Knockout Mapping library.

These are not definitive, so let me know if you REALLY disagree!

function PersonViewModel(data) {
  var self = this;
  
  self.firstName = ko.observable();
  self.lastName = ko.observable();
    
  ko.mapping.fromJS(data, {}, self);

  self.name = ko.computed(function(){
    return ko.unwrap(self.firstName) + " " + ko.unwrap(self.lastName);
  });
}

Class Definition

  • Define a class, I always name the class CapitalizedCase, as opposed to camelCase for variables.  Makes it clear when I'm about to instantiate a variable
  • I also always name ViewModel separately from just normal classes.  ViewModel are special, they are for data-binding.  To me, PersonViewModel is different from Person.

You can now create a view model like this.

var personVM = new PersonViewModel();

You can also define a class this way

var PersonViewModel = function(data){
  var self = this;
  
  // ...
};
  • But if you do it this way, understand that Javascript Hoisting is now in effect, and the class is not available until this line.
  • Also, remember the trailing semi-colon if you go for this assign variable syntax.

Property Definition & Knockout Mapping

ko.mapping.fromJS can be used to instantiate properties as a constructor.  But there are potential issues.  Consider:

function PersonViewModel(data) {
  var self = this;
  
  //self.firstName = ko.observable();
  //self.lastName = ko.observable();
  //if we don't define these...
    
  ko.mapping.fromJS(data, {}, self);

  self.name = ko.computed(function(){
    return ko.unwrap(self.firstName) + " " + ko.unwrap(self.lastName);
  });
}

var johnVM = new PersonViewModel( { firstName: "John", lastName: "Liu" });
var marcVM = new PersonViewModel( { firstName: "Marc" });
  • In marcVM, self.lastName is not created by ko.mapping and does not exist, and some binding statements will fail
  • So always declare (annoying) all the observable properties that you need.  Don't trust some REST response to always return data that you need.

Knockout Mapping Definition

I go with this style for defining Knockout Mapping definitions.

function PersonViewModel(data) {
  var self = this;
  self.firstName = ko.observable();
  //...
}
PersonViewModel.mapping = {
  create: function(options){
    return new PersonViewModel(options.data);
  },
  key: function(data) {
    return ko.unwrap(data.firstName);
  }
};
  • The reason is that as you'll see in next example, you need the mapping from time to time, might as well keep it in one place that you can access easily.
  • I have also seen people put mapping on ViewModel.prototype.mapping - the benefit I see with this is that within the class, you can refer to it via self.mapping (but I think that lacks clarity).

You can now do this:

var data = {firstName:"John"};
var person = ko.mapping.fromJS(data, PersonViewModel.mapping);

This gets more fun when you have nested Observable Arrays of Objects

function PeopleViewModel(data) {
  var self = this;
  self.teachers = ko.mapping.fromJS([], PersonViewModel.mapping);
  self.students = ko.mapping.fromJS([], PersonViewModel.mapping);
  
  ko.mapping.fromJS(data, {}, self);
}
PeopleViewModel.mapping = {
  create: function(options){
    return new PeopleViewModel(options.data);
  },
  teachers: PersonViewModel.mapping,
  students: PersonViewModel.mapping
  // Reuse the mapping defined above!
};

var data = { 
  teachers: [
    { firstName: "John" },
    { firstName: "Marc" }
  ],
  students: {
    { firstName: "Bob"}
  }
};
var peopleVM = new PeopleViewModel(data);
var index = peopleVM.teachers.mappedIndexOf({firstName:"Marc"});

// index == 1

Summary

Some notes on structuring your ViewModel classes for readability, avoiding binding issues and Knockout Mapping gotchas.

You can try the example in this Plunker

Moving Everyone and Everything to AngularJS

We are late on the boat.  But I'm describing the journey for us, and we are truly on the boat.

 

So in mid 2014, SharePoint Gurus decided that we'll move everyone to JavaScript.  Traditionally, we are very much an InfoPath, Workflows and Configuration-over-Customization type of Consultancy.

My background is hardcore ASP.NET so I get all the fun stuff of writing Full Trust and Sandbox Solutions.  Custom Web Parts, Feature Receivers and Workflow Activities.  Later, as more work moves to client-side scripting, I would write Full Trust REST service end-points that provide lots of functionality to our InfoPath and Front-End Developers.

As InfoPath goes on a slowly (but surely) spiral of death, we look forward to where we should be investing our company's time and skills.  I was asked to consider and plan out the migration path for the company.

What we looked at:

JQuery

JQuery itself was a good starting point, and possibly the simplest JavaScript library one should start with.  Traditionally, it's used for DOM manipulation, but it's usefulness was extended with jQuery Ajax and jQuery Deferred/Promise.  We use JQuery and the various plugins for JQuery for a lot of things.  Additionally, JQuery works very well with SPServices on SP2007 customizations.

KnockoutJS

KnockoutJS is a DataBinding library.  JQuery is great for creating Read Only, One-Way DOM creation (say, you query an REST end point and want to create a bunch of elements in a table or list).  But JQuery is terrible at keeping track of the UI and the Original JavaScript object for you to post that data back.

KnockoutJS fixes that problem.  The good side is that it's intuitive.  The downside is that because JavaScript properties doesn't have onChanged() method, KnockoutJS creates observable property wrappers instead, and the syntax is not as pretty.

DurandalJS

Since KnockoutJS is only a databinding library, when you want to start looking at creating Single Page Applications, you need more stuff.  You need a Module Loader.  You need a Routing System.  And you need View Composition.

Durandal uses KnockoutJS for data binding, and adds RequireJS for module loading and JQuery for AJAX calls.

Although I loved DurandalJS, ultimately I could not recommend it to the whole company because the creator Rob Eisenberg (@eisenbergeffect) moved to AngularJS (and later to Aurelia.io).  I am keen personally on Aurelia, but it is not ready to introduce to the whole company in 2014.

ASP.NET MVC

I personally LOVE ASP.NET MVC.  But here's the problem - we have developers who are used to ASP.NET WebForms, so for them there are two jumps: first they have to learn ASP.NET MVC and then they still have to learn JavaScript.

JavaScript is required learning.

And ASP.NET MVC needs SharePoint Provider-Hosted apps - we can't, for example, use it with SharePoint 2010 or SharePoint 2007.

We have not turned our backs to ASP.NET MVC forever, it's just for the immediate focus, we are fully committed to client-side (Front-End) development technologies.  A few of our advanced guys will double back and pick up ASP.NET MVC later (or NodeJS).

AngularJS

All choices aside, we decided on pushing forward with AngularJS.  For many in the team, they have experience with JQuery but not DurandalJS nor KnockoutJS - so there's not a lot of wasted learning.

For me, I always compare AngularJS to DurandalJS and the biggest issue I have personally is that AngularJS is...  too magical.  UN-intuitively magical.  There are a lot of very custom syntax that you just have to know.  If you didn't know, you wouldn't know it's available.  But if you are looking at someone else's work, you can generally work backwards and understand Ah that's how it fits.  I wish it was more intuitive.

The biggest advantage for AngularJS is just how much community momentum there is for it.  There are a lot of people that understand it well, and lots of people building applications with it, and discussing it on the Internet - anywhere you look.

Additionally, lots of AngularJS and SharePoint / Office 365 training is available online.  Which means that we don't have to re-invent every wheel.

As a company and for our teams, it is a very safe bet.

There are a few related technology in the stack that we are using:

Bootstrap and Font-Awesome both give the front-end developer two things:  Rapid layout and font-glyphs without mucking around outside of the HTML templates and JavaScript code.

AngularJS + TypeScript

Since AngularJS announced that it will be built in TypeScript, there has been a resurgence of activity on the TypeScript front.

If your team has a lot of C# developers, TypeScript is worth your time to invest into.  It will make your team more productive, and as a team, you will write much better code.

 

What I did NOT look at:

All that said, there's also a lot that's unsaid.  I did not look into Backbone, EmberJS or Telerik KendoUI.  The main reason really is that I was personally very happy with DurandalJS, and if it was up to me personally, I would have chose Aurelia to go next.  But the evaluation we went through is to decide which framework to pursue for the entire company.

I always consider that we should never stop learning.  In the JavaScript space this is even more true.  Just like back in 2008 we decided (in my previous company) that we will pursue JQuery, in 2014 - we made a similar decision to pursue AngularJS.

 

An Army of Front-End Developers

So as a whole, our team is turning from InfoPath designers into Front-End Developers.  We have mastered JQuery and now diving into the fun that is AngularJS Directives.

 

Aim to have An Army of Full-Stack Developers in the nearby future

Moving towards a proper MEAN stack.  There are other components to tackle next:

  • M - MongoDB (a NoSQL document database suitable for storing XML and JSON)
  • E - Express (a lightweight web server, aka IIS)
  • A - AngularJS (front-end)
  • N - NodeJS (run JavaScript on the server, aka C# or .NET Framework)
  • Everything will have to run Provider-Hosted, most likely on Azure

For now - we are Front-End developers and happy with just the UI and storage of the form contents.

  • A - AngularJS
  • S - SharePoint Library (storage of XML and JSON - can be easily loaded via client-side scripting)

Summary

https://twitter.com/alwaysbetonjs

https://twitter.com/alwaysbetonjs


Presenting "PhantomJS" at SPBizConf free online conference on June 18.

I will be presenting "Introducing PhantomJS: Headless Browser for your SharePoint/Online" in the SPBizConf on 18 June.

http://www.spbizconf.com/events/headless-in-sharepoint-phantomjs-will-blow-your-mind/

Despite the -JS in the name of the title, PhantomJS is not another Javascript library.  Instead, it is a headless browser that lets you automate many tasks involving a browser, and there are some very nifty tricks you can use this to build site directories or create PDF snapshot of documents and forms.

Timing

Technically, because of Timezone Differences, it will actually be the 19th of June at 7AM in the morning.  The session is pre-recorded and I will basically be watching it along with the attendees and replying to questions in the chat room.

More Online.  More content.

Online Conferences such as SPBizConf and Unity Online are a new thing for me, and has prompted me to start looking into setting up recording room at home for more, higher quality, recorded content to be made available from my local presentations.  I'm very excited to be able to participate in global conferences like this without the expense of having to do crazy travel - travelling from Australia to "anywhere" tend to get expensive very quickly.

Will it blow my mind?

The curious will see the old name of the session.  I've since calm down and renamed the title, but the old URL has to stick for link reasons.  You need to let me know if this session gave you great ideas about what sort of shenanigans you get up to afterwards.