使用 observables + 选择器和 ngx-cookie-service 在模板中显示 cookie 值的最佳方式是什么?

问题描述 投票:0回答:1

我很好奇是否有一种很好的方法来使用可观察量来实时获取 cookie 值,即“反应式”cookie? 可能的解决方案显示在服务中使用

this.cookieService.get("cookieName)
,但我需要一个选择器,以便我可以将 cookie 值用于我的观察。

angular ngrx ngx-cookie-service
1个回答
0
投票

使用 cookieService 的一种方法是创建如下服务:

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';
  }
}

在您的组件或服务中使用 CookieService:

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;
    });
  }
}

这是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();
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.