Last active
August 29, 2020 08:38
-
-
Save elpddev/d565f6e1a5da74f8addf34779bc89c81 to your computer and use it in GitHub Desktop.
AngularJs auth service directive #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; | |
} | |
} | |
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