angular - 在自定义结构指令 Angular 6+ 中使用 NGRX Observable

标签 angular observable ngrx subscription

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

@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 上的更改code>,除非 showEmpty 为 true。

最佳答案

您需要在订阅中创建或清除 View 。我建议您从输入创建另一个 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);
  }
}

关于angular - 在自定义结构指令 Angular 6+ 中使用 NGRX Observable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59143520/

相关文章:

typescript - RXJS Observable doSomething onComplete

javascript - ionic 查找是否通过 parent 点击事件点击了 child

javascript - 错误: Uncaught (in promise): TypeError: Cannot read property 'title' of undefined

c# - 我们如何在 IObservable<T> 上使用组函数,同时观察未完成或在热的、长时间运行的可观察对象上

typescript - 将多个参数传递给 rxjs 运算符

javascript - 在重新执行之前从 Observable 获取值

angular - 动画弹跳标记 AGM map

Angular 10 | ngrx 效果 |单元测试 |不能将类作为函数调用

javascript - 为什么我的 @Effect 在 Angular 6 中用 ngrx 覆盖现有状态?

rxjs - #ngrx 示例中的 SwitchMap 与 MergeMap