1

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?

spaleet
  • 838
  • 2
  • 10
  • 23
J.BizMai
  • 2,621
  • 3
  • 25
  • 49
  • would you consider doing the subscription from the service? (seems to be right object to have it, as it contains the `data`variable) – The Fabio Apr 18 '22 at 14:41

1 Answers1

1

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();
   }
}
Aakash Garg
  • 10,649
  • 2
  • 7
  • 25
  • I can use in a service, but I did not find how to do this. Can I a solution with service as well. I did not manage to insert watcher in a shared service... How can I do this ? – J.BizMai Apr 18 '22 at 14:53
  • 1
    even in that case you will be needing a service instance per component, after re iterating your problem the solution i have given above suits best. – Aakash Garg Apr 18 '22 at 14:54
  • I will test your solution with inheritance. – J.BizMai Apr 18 '22 at 15:48