From 649d9e6f183129f33b3be1d1dbbbe3c942fe229e Mon Sep 17 00:00:00 2001 From: Denes Papp Date: Mon, 29 Jul 2024 12:10:30 +0200 Subject: [PATCH] Switch to SafeObserver in MutationObserver classes to prevent errors during SSR (#654) --- libs/mutation-observer/src/classes/safe-observer.ts | 10 ++++++++++ .../src/directives/mutation-observer.directive.ts | 3 ++- .../src/services/mutation-observer.service.ts | 3 ++- 3 files changed, 14 insertions(+), 2 deletions(-) create mode 100644 libs/mutation-observer/src/classes/safe-observer.ts diff --git a/libs/mutation-observer/src/classes/safe-observer.ts b/libs/mutation-observer/src/classes/safe-observer.ts new file mode 100644 index 000000000..8e57210d0 --- /dev/null +++ b/libs/mutation-observer/src/classes/safe-observer.ts @@ -0,0 +1,10 @@ +export const SafeObserver = + typeof MutationObserver !== `undefined` + ? MutationObserver + : class implements MutationObserver { + observe(): void {} + disconnect(): void {} + takeRecords(): MutationRecord[] { + return []; + } + }; diff --git a/libs/mutation-observer/src/directives/mutation-observer.directive.ts b/libs/mutation-observer/src/directives/mutation-observer.directive.ts index ec7ea3129..47df7ccf7 100644 --- a/libs/mutation-observer/src/directives/mutation-observer.directive.ts +++ b/libs/mutation-observer/src/directives/mutation-observer.directive.ts @@ -8,6 +8,7 @@ import { Output, } from '@angular/core'; +import {SafeObserver} from '../classes/safe-observer'; import {MUTATION_OBSERVER_INIT} from '../tokens/mutation-observer-init'; import {mutationObserverInitFactory} from '../utils/mutation-observer-init-factory'; @@ -22,7 +23,7 @@ import {mutationObserverInitFactory} from '../utils/mutation-observer-init-facto }, ], }) -export class MutationObserverDirective extends MutationObserver implements OnDestroy { +export class MutationObserverDirective extends SafeObserver implements OnDestroy { @Output() readonly waMutationObserver = new EventEmitter(); diff --git a/libs/mutation-observer/src/services/mutation-observer.service.ts b/libs/mutation-observer/src/services/mutation-observer.service.ts index 437494100..31c2d4f39 100644 --- a/libs/mutation-observer/src/services/mutation-observer.service.ts +++ b/libs/mutation-observer/src/services/mutation-observer.service.ts @@ -1,6 +1,7 @@ import {ElementRef, Inject, Injectable} from '@angular/core'; import {Observable} from 'rxjs'; +import {SafeObserver} from '../classes/safe-observer'; import {MUTATION_OBSERVER_INIT} from '../tokens/mutation-observer-init'; @Injectable() @@ -10,7 +11,7 @@ export class MutationObserverService extends Observable { - const observer = new MutationObserver(records => { + const observer = new SafeObserver(records => { subscriber.next(records); });