Как избежать двойной подписки в нескольких директивах

#javascript #angular #typescript #rxjs #ngrx

Вопрос:

Я работаю с ngrx, у меня есть один селектор «роль», на который мне нужно подписаться, чтобы узнать свою роль в приложении. Мне нужны две директивы, которые мне нужно использовать для управления грантами в заявке. Я создал две директивы «isAdmin» и «isCustomer» на основе ролей, которые у меня есть. Я хочу сделать единую подписку и управлять значением в обеих созданных мной директивах. Есть какие-нибудь предложения?

     @Directive({
      selector: '[isAdmin]',
    })
    export class IsAdminDirective implements OnInit, OnDestroy {
      role = this.sandbox.Role  // this is a selector;
      isAdmin = false;

      constructor(private sandbox: Sandbox, private templateRef: TemplateRef<any>, private viewContainerRef: ViewContainerRef) {}

      ngOnInit() {
        this.role.pipe().subscribe(res => {
          this.isAdmin = res.toLowerCase() === 'admin' ? true : false;

          if (this.isAdmin) {
            this.viewContainerRef.createEmbeddedView(this.templateRef);
          } else {
            this.viewContainerRef.clear();
          }
        });
      }


    }

    @Directive({
      selector: '[isCustomer]',
    })
    export class IsCustomerDirective implements OnInit, OnDestroy {
      role = this.sandbox.Role;
      isCustomer = false;


      constructor(private sandbox: Sandbox, private templateRef: TemplateRef<any>, private viewContainerRef: ViewContainerRef) {}

      ngOnInit() {
        this.role.pipe().subscribe(res => {
          this.isCustomer = res.toLowerCase() === 'customer' ? true : false;

          if (this.isCustomer) {
            this.viewContainerRef.createEmbeddedView(this.templateRef);
          } else {
            this.viewContainerRef.clear();
          }
        });
      }

   
    }

  
 

Комментарии:

1. Ты пробовал publishReplay(1), refCount() ?