Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 1. LoginService
- @Injectable()
- export class LoginService {
- constructor(
- private http: Http,
- private auth: AuthService,
- ) { }
- login() {
- this.http.get('/login').subscribe(() => {
- this.auth.setAuthenticated(true);
- })
- }
- logout() {
- this.auth.setAuthenticated(false);
- }
- }
- // 2. AuthService
- @Injectable()
- export class AuthService {
- public isAuthenticated$: Subject<boolean> = new Subject();
- public setAuthentication(value: boolean) {
- this.isAuthenticated$.next(value);
- }
- }
- // 3. Use in Directive
- export class ifLoggedDirective implements OnDestroy {
- $auth: Subscription;
- constructor(
- private auth: AuthService,
- private template: TemplateRef<any>,
- private view: ViewContainerRef
- ) {
- this.$auth = auth.isAuthenticated$
- .do(() => this.view.clear())
- .subscribe(authenticated => {
- if (authenticated)) {
- this.view.createEmbeddedView(this.template);
- }
- });
- }
- ngOnDestroy() {
- if (this.$auth) {
- this.$auth.unsubscribe();
- }
- }
- }
- ```
- ]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement