user2356169
user2356169

Reputation: 73

Trying to inject $window into angular factory using typescript

I am trying to inject $winow into my factory.

Here is my factory and class definition

 export interface IAuthToken {
 }

 export class AuthToken implements IAuthToken {
     storage: Storage;
     constructor(private $window: ng.IWindowService) {
        this.storage = this.$window.localStorage;
     }

    factory.$inject = ['$window'];
    function factory($window: ng.IWindowService): IAuthToken {
        return new AuthToken(this.$window);
    }

    angular
        .module('test')
        .factory('app.common.auth.AuthToken', factory);
}

When I debug the code the $window is always set to undefined. I have attempted to add the injection when registering the factory itself and I still get the $window as undefined?

function factory($window: ng.IWindowService): IAuthToken {
    return new AuthToken(this.$window);
}

angular
    .module('test')
    .factory('app.common.auth.AuthToken', ['$window',factory]);

Any help would be greatly appreciated. Thanks in advance.

Upvotes: 0

Views: 6535

Answers (1)

John Bonfardeci
John Bonfardeci

Reputation: 476

You're almost there. You need to move your factory declarations outside of your AuthToken class and just below it. You could change to this:

```

export interface IAuthToken {}

export class AuthToken implements IAuthToken {

    static Id: string = 'app.common.auth.AuthToken';

    storage: Storage;
    constructor(private $window: ng.IWindowService) {
        this.storage = this.$window.localStorage;
    }
}

function factory($window: ng.IWindowService): IAuthToken {
    return new AuthToken($window);
}

angular
    .module('test')
    .factory(AuthToken.Id, ['$window', factory]);

```

Upvotes: 3

Related Questions