How do I access the service provider when registering using typescript class

2.5k views Asked by At

The following service provider registers successfully. Other controllers can use the service without trouble. My question is how to access the provider in order to configure it before the service is instantiated by the $injector service?

module apiService{

    export interface IBaseService{
        leagueID: number;
    }

    export interface IApiBaseServiceProvider extends ng.IServiceProvider{
        setLeagueID(leagueID: number): void;
        $get(): IBaseService;
    }

    class BaseServiceProvider implements IApiBaseServiceProvider{

        private _leagueID: number;

        $get(){
            return new BaseService(this._leagueID);
        }

        setLeagueID(leagueID: number){
            this._leagueID = leagueID;
        };


    }

    class BaseService implements IBaseService{

        constructor(private _leagueID: number){};

        get leagueID(){
            return this._leagueID;
        }

    }

    angular.module('apiService').provider('apiService.baseService', BaseServiceProvider);

}

I've tried using the class name as the accessor but the entire application fails when doing so.

angular.module('apiService').config(['BaseServiceProvider', function(baseServiceProvider: IApiBaseServiceProvider){
    baseServiceProvider.setLeagueID(12);    
}]);

The documentation only shows an example where a named function is used to instantiate the provider. Later in the explanation, the named function's name is used to access the provider.

Because a TypeScript class is used in the above example there is no named function to use to access the provider. So, how does one configure the provider when using a TypeScript class?

1

There are 1 answers

2
PSL On BEST ANSWER

Problem is with your registration of provider. Instead of

  angular.module('apiService').provider('apiService.baseService', BaseServiceProvider);

do:

 angular.module('apiService').provider('BaseService', BaseServiceProvider);

and access in the config phase like you do, BaseServiceProvider (postfix word Provider). When injecting the provider instance anywhere else you could just use BaseService. So basically you don't inject with the class name, instead you inject with the name it is registered with.