Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save elpddev/58dbd6727eceeb328eb67e7276b7e6f7 to your computer and use it in GitHub Desktop.
Save elpddev/58dbd6727eceeb328eb67e7276b7e6f7 to your computer and use it in GitHub Desktop.
Service directive in action #angularjs #medium #article-hierarchical-di-ng
class AuthService {
static $inject = ['$http'];
private token: string;
constructor($http: IHttpService) {}
getToken() {
if (_.isNil(this.token)) {
this.token = $http.get('my-site.example.com/auth');
}
return this.token;
}
}
class EastAndorAuthService {
static $inject = ['$http'];
private token: string;
constructor($http: IHttpService) {}
getToken() {
if (_.isNil(this.token)) {
this.token = $http.get('east-andor.example.com/auth');
}
return this.token;
}
}
// using the same `auth` key to register EastAndoAuthService
angular.directive('auth', [function auth() {
return {
restrict: 'A',
controller: ['$attrs', '$injector', function controller($attrs, $injector) {
this.service = switchOn({
'': () => $injector.invoke(AuthService),
eastAndor: () => $injector.invoke(EastAndorAuthService),
}, $attrs.auth);
}],
};
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment