Advertisement
fabiobiondi

Angular: RxJS, Subject and Directives

Jun 12th, 2017
489
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.11 KB | None | 0 0
  1.  
  2. // 1. LoginService
  3. @Injectable()
  4. export class LoginService {
  5.  
  6. constructor(
  7. private http: Http,
  8. private auth: AuthService,
  9. ) { }
  10.  
  11. login() {
  12. this.http.get('/login').subscribe(() => {
  13. this.auth.setAuthenticated(true);
  14. })
  15. }
  16.  
  17. logout() {
  18. this.auth.setAuthenticated(false);
  19. }
  20. }
  21.  
  22.  
  23.  
  24.  
  25. // 2. AuthService
  26. @Injectable()
  27. export class AuthService {
  28.  
  29. public isAuthenticated$: Subject<boolean> = new Subject();
  30.  
  31. public setAuthentication(value: boolean) {
  32. this.isAuthenticated$.next(value);
  33. }
  34. }
  35.  
  36.  
  37. // 3. Use in Directive
  38.  
  39. export class ifLoggedDirective implements OnDestroy {
  40. $auth: Subscription;
  41.  
  42. constructor(
  43. private auth: AuthService,
  44. private template: TemplateRef<any>,
  45. private view: ViewContainerRef
  46. ) {
  47. this.$auth = auth.isAuthenticated$
  48. .do(() => this.view.clear())
  49. .subscribe(authenticated => {
  50. if (authenticated)) {
  51. this.view.createEmbeddedView(this.template);
  52. }
  53. });
  54. }
  55.  
  56. ngOnDestroy() {
  57. if (this.$auth) {
  58. this.$auth.unsubscribe();
  59. }
  60. }
  61. }
  62.  
  63. ```
  64. ]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement