【问题标题】:Using an NGRX Observable inside of a custom Structural Directive Angular 6+在自定义结构指令Angular 6+中使用NGRX Observable
【发布时间】:2020-03-27 08:06:00
【问题描述】:

我正在尝试编写一个使用 ngrx 存储的自定义结构指令。在商店里,我有一面旗帜,告诉我是否应该展示一些组件。我想让我的自定义指令订阅该商店,并根据该标志是否为真或该标志是否为假但组件具有应呈现的数据来呈现组件。代码如下:

@Directive({ selector: '[showIfExists]' })
export class ShowIfExistsDirective {

  showEmpty$ = this.store.select(getShowHideState).subscribe((value) => {
    this.showEmpty = value;
  });
  showEmpty: boolean;

  constructor(
    private templateRef: TemplateRef<any>,
    private viewContainer: ViewContainerRef,
    private store: Store<AppState>) {
  }

  ngOnDestroy() {
    this.showEmpty$.unsubscribe();
  }

  @Input() set showIfExists(condition: boolean) {
    if (this.showEmpty || (!this.showEmpty && condition)) {
      this.viewContainer.createEmbeddedView(this.templateRef);
    } else {
      this.viewContainer.clear();
    }
  }
}

我最终看到的是订阅正确地更新了我的showEmpty 属性,但是set showIfExists 不会响应showEmpty 上的更改,除非showEmpty 为真。

【问题讨论】:

    标签: angular observable ngrx subscription


    【解决方案1】:

    您需要在订阅中创建或清除视图。我建议您从输入中创建另一个 Observable (BehaviorSubject)。

    @Directive({ selector: '[showIfExists]' })
    export class ShowIfExistsDirective {
    
      showEmpty$: Observable<boolean> = this.store.select(getShowHideState);
      showIfExists$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
    
      constructor(
        private templateRef: TemplateRef<any>,
        private viewContainer: ViewContainerRef,
        private store: Store<AppState>) {
    
        combineLatest([this.showEmpty$, this.showIfExists$]).pipe(
          distinctUntilChanged(),
          map(([showEmpty, showIfExists]) => showEmpty || condition), // !showEmpty is btw redundant
          // don't forget to unsubscribe your way
        ).subscribe(activate => {
          if (activate) this.viewContainer.createEmbeddedView(this.templateRef)
          else this.viewContainer.clear();
        });
      }
    
      @Input() set showIfExists(condition: boolean) {
        this.showIfExists$.next(condition);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-02-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-05
      • 2019-04-09
      • 1970-01-01
      • 2015-10-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多