Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save elpddev/d565f6e1a5da74f8addf34779bc89c81 to your computer and use it in GitHub Desktop.
Save elpddev/d565f6e1a5da74f8addf34779bc89c81 to your computer and use it in GitHub Desktop.
AngularJs auth service directive #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;
}
}
angular.directive('auth', [function auth() {
return {
restrict: 'A',
controller: AuthService,
};
}]);
/////////////////////////
class MoviesService {
static $inject = ['$http'];
movies = Promise.resolve([]);
constructor(
private $http: IHttpService,
) {}
getMovies() {
// require directives are avaiable when and after $onInit.
if (_.isNil(this.auth)) {
return [];
}
if (_.isNil(this.movies)) {
this.movies = this.auth.getToken()
.then((token) => {
return $http.get('my-site.example.com/movies', {
headers: {
Authorization: token,
},
});
});
}
return this.movies;
}
}
angular.directive('movies', [function movies() {
return {
restrict: 'A',
require: {
auth: '^',
},
controller: MoviesService,
};
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment