What's the best way to show the cookie value in the template using observables + selectors with ngx-cookie-service?

134 views Asked by At

I'm curious is there a nice way to use observables to get a cookie value in real time, a "reactive" cookie? The possible solutions show using this.cookieService.get("cookieName) in services, but I need a selector so that I can use the cookie value for my obseravbles.

1

There are 1 answers

2
moh On

One way of using cookieService is by creating a service like below:

import { Injectable } from '@angular/core';
import { Observable, BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class CookieService {
  private cookieValueSubject: BehaviorSubject<string | null>;

  constructor() {
    this.cookieValueSubject = new BehaviorSubject<string | null>(this.getCookie('yourCookieName'));
  }

  getCookieValue(): Observable<string | null> {
    return this.cookieValueSubject.asObservable();
  }

  updateCookieValue(): void {
    this.cookieValueSubject.next(this.getCookie('yourCookieName'));
  }

  private getCookie(cookieName: string): string | null {
    return 'yourCookieValue';
  }
}

Use the CookieService in your component or service:

import { Component, OnInit } from '@angular/core';
import { CookieService } from 'path-to-your-cookie-service';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css'],
})
export class YourComponent implements OnInit {
  cookieValue: string | null;

  constructor(private cookieService: CookieService) {}

  ngOnInit(): void {
    this.cookieService.getCookieValue().subscribe((value) => {
      this.cookieValue = value;
    });
  }
}

Here is the Code of HostListener

import { Directive, Output, EventEmitter, HostListener } from '@angular/core';
import { Observable } from 'rxjs';

@Directive({
  selector: '[cookieObserver]',
})
export class CookieObserverDirective {
  @Output() cookieValueChange: EventEmitter<string | null> = new EventEmitter<string | null>();

  constructor() {}

  @HostListener('document:cookieChange', ['$event'])
  onCookieChange(event: Event): void {
    const cookieValue = this.getCookie('yourCookieName');
    this.cookieValueChange.emit(cookieValue);
  }

  private getCookie(cookieName: string): string | null {
    return 'yourCookieValue';
  }

  getCookieValue(): Observable<string | null> {
    return this.cookieValueChange.asObservable();
  }
}