My current project is utilizing Angular version 15.2.10. In order to monitor cookie changes, I have developed an Angular service that taps into the CookieStore API. Below you can find a snippet of my existing code:
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();
});
}
}
The above code functions correctly but I am looking to enhance it by adding the ability to cancel the subscription. I attempted to save the subscription for later use:
const sub = window.cookieStore.addEventListener( ...);
console.log("sub " + sub)
However, this approach does not return anything and the output message reads as follows:
sub undefined
What would be the best way for me to obtain a reference for the created subscription so that I can utilize it later to cancel the subscription?