In an Angular application, I need for user preferences change to save in the database (by back api). This code should be use in all pages (components).
I got this code :
export class OneComponent implements OnInit, OnDestroy {
watcherSubscriptionForUser: Subscription = Subscription.EMPTY;
async ngOnInit() {
this.watcherSubscriptionForUser = this.libUserService.data.subscribe((currentUser: UserItem) => {
// Preferences changed => call api to save data
});
}
ngOnDestroy(): void {
this.watcherSubscriptionForUser.unsubscribe();
}
}
I did not manage to use Subscription
inside a service.
How can I factorize this peace of code to use for all my concerned components?
CodePudding user response:
If you really don't want to use service, then do this.
Create a Base Class like below :-
// Remove @Directive if you are using angular < v9.
@Directive()
export class BaseWatcherClass {
watcherSubscriptionForUser: Subscription = Subscription.EMPTY;
libUserService;
constructor(service) {
this.libUserService = service;
}
ngOnInit() {
this.watcherSubscriptionForUser = this.libUserService.data.subscribe((currentUser: UserItem) => {
// Preferences changed => call api to save data
});
}
ngOnDestroy(): void {
this.watcherSubscriptionForUser.unsubscribe();
}
}
Then extend this class :-
export class OneComponent extends BaseWatcherClass implements OnInit, OnDestroy {
constructor(libUserService) {
super(libUserService)
}
ngOnInit() {
// other piece of code, this ngOnInit is only required if you want to have some other logic with default one else you can skip it.
super.ngOnInit();
}
}