Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save elpddev/58dbd6727eceeb328eb67e7276b7e6f7 to your computer and use it in GitHub Desktop.

Select an option

Save elpddev/58dbd6727eceeb328eb67e7276b7e6f7 to your computer and use it in GitHub Desktop.

Revisions

  1. elpddev created this gist Aug 29, 2020.
    44 changes: 44 additions & 0 deletions article-hierarchical-di-service-directive-heirarchy-in-action.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,44 @@
    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);
    }],
    };
    }]);