Created
August 29, 2020 09:21
-
-
Save elpddev/58dbd6727eceeb328eb67e7276b7e6f7 to your computer and use it in GitHub Desktop.
Service directive in action #angularjs #medium #article-hierarchical-di-ng
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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