如何在角度服务中取消对 window.cookieStore.addEventListener('change', ) 的订阅

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

我创建了一个 Angular 服务,它可以利用 CookieStore Api 监听 cookie 更改。 我当前的代码如下所示:

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

此代码按预期工作。 最重要的是,我希望能够取消订阅。我尝试存储订阅以供以后使用:

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

但是这段代码没有返回,输出消息是:

sub undefined

如何检索已创建订阅的引用,然后使用它来取消订阅?

javascript angular typescript subscription cookiestore
1个回答
0
投票

https://developer.mozilla.org/zh-CN/docs/Web/API/EventTarget/removeEventListener

function handleChange() {
  // ...
}

// sub
window.cookieStore.addEventListener('change', handleChange);
// unsub
window.cookieStore.removeEventListener('change', handleChange);
© www.soinside.com 2019 - 2024. All rights reserved.