1
- import { inject , Injectable , OnDestroy } from '@angular/core' ;
1
+ import { DestroyRef , inject , Injectable } from '@angular/core' ;
2
2
import { TranslocoService } from '@jsverse/transloco' ;
3
- import { BehaviorSubject , Subscription } from 'rxjs' ;
3
+ import { BehaviorSubject } from 'rxjs' ;
4
4
import { distinctUntilChanged , filter , map } from 'rxjs/operators' ;
5
5
6
6
import { isLocaleFormat , toDate } from './helpers' ;
@@ -27,7 +27,7 @@ import {
27
27
@Injectable ( {
28
28
providedIn : 'root' ,
29
29
} )
30
- export class TranslocoLocaleService implements OnDestroy {
30
+ export class TranslocoLocaleService {
31
31
private translocoService = inject ( TranslocoService ) ;
32
32
private langLocaleMapping = inject ( TRANSLOCO_LOCALE_LANG_MAPPING ) ;
33
33
private defaultLocale = inject ( TRANSLOCO_LOCALE_DEFAULT_LOCALE ) ;
@@ -39,16 +39,26 @@ export class TranslocoLocaleService implements OnDestroy {
39
39
40
40
private _locale =
41
41
this . defaultLocale || this . toLocale ( this . translocoService . getActiveLang ( ) ) ;
42
- private locale : BehaviorSubject < Locale > = new BehaviorSubject ( this . _locale ) ;
43
- private subscription : Subscription | null = this . translocoService . langChanges$
44
- . pipe (
45
- map ( ( lang ) => this . toLocale ( lang ) ) ,
46
- filter ( Boolean ) ,
47
- )
48
- . subscribe ( ( locale : Locale ) => this . setLocale ( locale ) ) ;
42
+ private locale = new BehaviorSubject < Locale > ( this . _locale ) ;
49
43
50
44
localeChanges$ = this . locale . asObservable ( ) . pipe ( distinctUntilChanged ( ) ) ;
51
45
46
+ constructor ( ) {
47
+ inject ( DestroyRef ) . onDestroy ( ( ) => {
48
+ // Complete subjects to release observers if users forget to unsubscribe manually.
49
+ // This is important in server-side rendering.
50
+ this . locale . complete ( ) ;
51
+ } ) ;
52
+
53
+ this . translocoService . langChanges$
54
+ . pipe (
55
+ map ( ( lang ) => this . toLocale ( lang ) ) ,
56
+ filter ( Boolean ) ,
57
+ )
58
+ // Note: No need to unsubscribe because `lang` is completed by the `TranslocoService`.
59
+ . subscribe ( ( locale : Locale ) => this . setLocale ( locale ) ) ;
60
+ }
61
+
52
62
getLocale ( ) {
53
63
return this . _locale ;
54
64
}
@@ -143,13 +153,6 @@ export class TranslocoLocaleService implements OnDestroy {
143
153
return this . localeCurrencyMapping [ locale ] || this . defaultCurrency ;
144
154
}
145
155
146
- ngOnDestroy ( ) {
147
- this . subscription ?. unsubscribe ( ) ;
148
- // Caretaker note: it's important to clean up references to subscriptions since they save the `next`
149
- // callback within its `destination` property, preventing classes from being GC'd.
150
- this . subscription = null ;
151
- }
152
-
153
156
private toLocale ( val : string | Locale ) : Locale {
154
157
if ( this . langLocaleMapping [ val ] ) {
155
158
return this . langLocaleMapping [ val ] ;
0 commit comments