Javascript 如何避免在多个指令中重复订阅

Javascript 如何避免在多个指令中重复订阅,javascript,angular,typescript,rxjs,ngrx,Javascript,Angular,Typescript,Rxjs,Ngrx,我与ngrx合作,我需要订阅一个选择器“角色”,以了解我在应用程序中的角色。我需要两条指令,用于管理应用程序中的拨款。 我根据我的角色创建了两个指令“isAdmin”和“isCustomer”。我想做一个订阅并管理我创建的两个指令中的值。有什么建议吗 @Directive({ selector: '[isAdmin]', }) export class IsAdminDirective implements OnInit, OnDestroy {

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

   
    }

  
@指令({
选择器:“[isAdmin]”,
})
导出类IsAdminDirective实现OnInit、OnDestroy{
role=this.sandbox.role//这是一个选择器;
isAdmin=false;
构造函数(私有沙盒:沙盒,私有templateRef:templateRef,私有viewContainerRef:viewContainerRef){}
恩戈尼尼特(){
this.role.pipe().subscribe(res=>{
this.isAdmin=res.toLowerCase()==“admin”?true:false;
if(this.isAdmin){
this.viewContainerRef.createEmbeddedView(this.templateRef);
}否则{
this.viewContainerRef.clear();
}
});
}
}
@指示({
选择器:“[isCustomer]”,
})
导出类IsCustomerDirective实现OnInit、OnDestroy{
role=this.sandbox.role;
isCustomer=false;
构造函数(私有沙盒:沙盒,私有templateRef:templateRef,私有viewContainerRef:viewContainerRef){}
恩戈尼尼特(){
this.role.pipe().subscribe(res=>{
this.isCustomer=res.toLowerCase()=“customer”?true:false;
if(this.isCustomer){
this.viewContainerRef.createEmbeddedView(this.templateRef);
}否则{
this.viewContainerRef.clear();
}
});
}
}

您是否尝试过
publishReplay(1),refCount()