Search code examples
angularjsangularfireobjectfactory

AngularFire ObjectFactory Childobjects cause Circular Dependency


Using AngularFire, I am extending the object factories in order to have encapsulated data and to allow specific features, as explained in the official tutorial. I have a data structure like the following:

{
    'articles': {
        'article-asd876a': {
            title: 'abc',
            text: 'lorem ipsum ...',
            comments: {
                'comment-ad4e6a': true,
                'comment-dsd9a7': true
            }
        }
    },
    'comments': {
        'comment-ad4e6a': {
            text: 'comment text1',
            articleId: 'article-asd876a'
        },
        'comment-dsd9a7': {
            text: 'comment text2',
            articleId: 'article-asd876a'
        }
    }
}

Now I would love to be able to do this:

var article = new Article(8); // Returns the object created by my object factory, fetching data from firebase
var comments = article.getComments(); // Returns an array of type Comment
var firstText = comments[0].getText();
var article2 = comments[0].getArticle(); // article2 === article

But this fails for me on many levels. One of them being: In Article, I can only store the Comment ID, and therefore have to recreate the Comment Object using new Comment(commentId), for which I need to inject Comment into Article. The same is true for Comment, so that I end up with a circular dependency Article -> Comment -> Article. The following fiddle shows the behavior: http://jsfiddle.net/michaschwab/v0qzdgtq/.

What am I doing wrong? Is this a bad concept/structure for angular? Thanks!!


Solution

  • What am I doing wrong? Is this a bad concept/structure for angular? Thanks!!

    You are creating circular dependencies.

    I can do var Comment = $injector.get('Comment'); to avoid the error, is that the best solution?

    I see two solutions:-

    1) Lazy injecting solution (you suggested yourself)

    This is the best solution to avoid those circular dependencies in AngularJS. Although looking at the AngularFire documentation you are into an uncharted territory as some of these things in AngularFire are experimental in nature.

    Here is the working fiddle from your

    var Comment = $injector.get('Comment');
    

    You are essentially lazy injecting your references.

    http://jsfiddle.net/yogeshgadge/ymxkt6up/5/

    2) Module Run block:

    With this option you may be able to inject those dependencies into your factories instead of using $injector.