how to cancel subscription to window.cookieStore.addEventListener('change', ) in angular...

Discussão em 'Angular' iniciado por fascynacja, Novembro 22, 2024.

  1. fascynacja

    fascynacja Guest

    I have created an angular service which can listen to cookie changes by leveraging the CookieStore Api. My current code looks as follows:

    type CookieChangeType = {
    name: string,
    value: string,
    expires: Date,
    domain: string,
    }

    interface CookieChangeEvent extends Event {
    changed: CookieChangeType[]
    }

    type CookieStore = {
    addEventListener: Window["addEventListener"]
    }

    declare global {
    interface Window {
    cookieStore: CookieStore;
    addEventListener(type: String, listener: (this: Window, ev: CookieChangeEvent) => any, useCapture?: boolean): void;
    }
    }

    export class CookieConsentCommonsService {


    subscribeToConsentCookieChange(callback: () => void): void {
    window.cookieStore.addEventListener('change', (event: CookieChangeEvent) => {
    console.log(`Cookie changed: ${change.name} = ${change.value}`);
    callback();
    });
    }
    }


    This code works as expected. On the top of that I would like to be able to cancel the subscription. I have tried to store the subscription for later :

    const sub = window.cookieStore.addEventListener( ...);
    console.log("sub " + sub)


    But there is no return from this code and the output message is:

    sub undefined


    How can I retrieve a reference for created subscription and later on use it to cancel the subscription?

    Continue reading...

Compartilhe esta Página