admin管理员组文章数量:1122832
I am using angular: 15.2.10 for my project. 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?
I am using angular: 15.2.10 for my project. 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?
Share Improve this question edited Nov 22, 2024 at 11:25 fascynacja asked Nov 22, 2024 at 9:27 fascynacjafascynacja 2,7785 gold badges27 silver badges51 bronze badges2 Answers
Reset to default 4https://developer.mozilla.org/zh-CN/docs/Web/API/EventTarget/removeEventListener
function handleChange() {
// ...
}
// sub
window.cookieStore.addEventListener('change', handleChange);
// unsub
window.cookieStore.removeEventListener('change', handleChange);
or
const controller = new AbortController();
// sub
window.cookieStore.addEventListener('change', handleChange, { signal: controller.signal });
// unsub
controller.abort();
ts
// Cookie interface definition
interface Cookie {
name: string;
value: string;
expires?: Date | null; // Optional expiration time
path?: string; // Optional path
domain?: string; // Optional domain
secure?: boolean; // Optional secure flag
sameSite?: 'lax' | 'strict' | 'none'; // Optional SameSite attribute
}
// CookieStore interface inheriting from EventTarget
interface CookieStore extends EventTarget {
get(name: string): Promise<Cookie | null>;
getAll(): Promise<Cookie[]>;
set(cookie: Cookie): Promise<void>;
delete(name: string): Promise<void>;
}
// Adding CookieStore to the global window object
declare global {
interface Window {
cookieStore: CookieStore;
}
}
You can try the rxjs
way of handling events using fromEvent
, I use subscription
to unsubscribe the observable stream when the component is destroyed.
cookieStore = (window as any)['cookieStore'];
listener = (callback: () => void, event: any) => {};
private sub: Subscription = new Subscription();
ngOnInit() {
this.subscribeToConsentCookieChange(() => {});
}
async subscribeToConsentCookieChange(callback: () => void) {
this.sub.add(
fromEvent<any>(this.cookieStore, 'change')
.subscribe((event: any) => {
console.log(`Cookie changed: `, event);
callback();
})
);
// this.cookieStore.addEventListener('change', (event: any) => {
// console.log(`Cookie changed`);
// callback();
// });
await this.cookieStore.set('test', 'asdf');
}
ngOnDestroy() {
this.sub.unsubscribe();
}
本文标签:
版权声明:本文标题:javascript - how to cancel subscription to window.cookieStore.addEventListener('change', ) in angular service - 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736304821a1932370.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论