1

I use AngularJS with Typescript and the definitions from DefinitelyTyped.

I define my services and configs like this:

module MyModule {
    export module Services {
        export class MyService {
            constructor() {
                console.log(this); // this refers to service instance, as expected
            }
        }
    }
}

module MyModule {
    export module Configurations {
        export class MyConfiguration {
            constructor() {
                console.log(this); // this refers to Window!?
            }
        }
    }
}

And register them like this:

var app = angular.module('MyApp', ...);
app.config(MyModule.Configurations.MyConfiguration);
app.service('MyService', MyModule.Services.UserService);

This works just fine but I noticed that this is resolved differently: when the service is instantiated the console logs [object Object] as expected, referencing the instance of the service. But when the config is processed, the console logs [object Window], the global window object.

Why?

2 Answers 2

2
  1. angular.config required to pass function, not class, this refers to window, this is fine.
  2. you don't need to access this in config at all, in config you can configure your providers and so on.

Also your code can be simplified like this:

module MyModule.Services {
    export class MyService {
        constructor() {
            console.log(this); // this refers to service instance, as expected
        }
    }
}

module MyModule.Configurations {
    export function myConfiguration(yourProvider1, yourProvider2) {
        //config injectables, you don't need to access this at all
    }
}

var app = angular.module('MyApp', []);
app.config(MyModule.Configurations.myConfiguration);
app.service('MyService', MyModule.Services.MyService);

As you can see, you don't need to nest your modules, BTW I suggest to use new namespace syntax :)

Sign up to request clarification or add additional context in comments.

Comments

1

I believe it is because the configuration is a used to setup settings for the whole module and the only way this is possible is to load it onto the window.

A service is only accessible if injected by the DI system and it is also instantiated as a singelton, why it must have a context of its own.

I am sure to have read about this somewhere, but I cant find a reference for now. I'll get back to you if I find it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.