我如何对 Angular 中的多个组件使用相同的观察者(订阅)?

How can i use the same watcher (Subscription) for several components in Angular?

在 Angular 应用程序中, 我需要更改用户首选项以保存在数据库中(返回 api)。 此代码应在所有页面(组件)中使用。

我得到了这个代码:

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();
    }

}

我没能在服务中使用 Subscription。 我如何分解这些代码的和平以用于我所有相关的组件?

如果你真的不想使用服务,那就这样做。

像下面这样创建一个基地 Class :-

// 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();
  }
}

然后扩展这个 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();
   }
}