【问题标题】:using rxjs subject to show and hide component in Angular 7使用 rxjs 主题在 Angular 7 中显示和隐藏组件
【发布时间】:2020-01-15 00:53:14
【问题描述】:

我有 3 个组件 inquiry-forminquiry-responseinquiry-summary 在某些情况下,这个组件可以隐藏和显示,我使用rxjssubject在组件之间发送数据,这是场景:

查询表格

  • 有 2 个 div
  • 用户输入id号(重定向到查询响应1),它将在查询表上隐藏2个div

查询-回复

  • 有 2 格
  • 更改 ID 按钮重定向到查询表 1
  • 选中复选框并提交按钮重定向到查询摘要 2

在这里我创建了stackblitz,这是我尝试过的:

inquiry-store.service.ts

  private hideContainer = new Subject<boolean>();
  public hideContainer$ = this.hideContainer.asObservable
  ();

  private summary = new Subject<boolean>();
  public summary$ = this.summary.asObservable
  ();

  private checkbox = new Subject<boolean>();
  public checkbox$ = this.checkbox.asObservable
  ();

  setHideContainer(data: boolean) {
  this.hideContainer.next(data);
  }

 setSummary(data: boolean) {
  this.summary.next(data);
  }

setCheckbox(data: boolean) {
  this.checkbox.next(data);
  }
}

并且在每个组件中都会根据条件订阅这个,

inquiry-form.component.ts

      ngOnInit() {
            this.inquiryStore.hideContainer$.subscribe(istrue => {
          this.isHasSummon = istrue;
        });
      }

      onSubmit(): void {
        this.inquiryService.getData(data).subscribe((res: any)=> {
          this.inquiryStore.setSummon(res);
          this.isHasSummon = true;

        })
      }

inquiry-response.component.ts

  ngOnInit() {

    this.inquiryStore.hideContainer$.subscribe(isTrue => {
      this.showChangeId = isTrue;
    });

    this.inquiryStore.checkbox$.subscribe(isTrue => {
          this.hideCheckbox = isTrue;
    })
  }

  submitSelectedCheckbox() {
    this.inquiryStore.setSummary(false)
    this.hideCheckbox = true;
 }

   goToInquiryForm() {
    this.inquiryStore.setHideContainer(false);
    this.isShowResponse = false;
  }
}

我遇到了一些问题,在查询响应1中,单击更改ID后,它将重定向到查询表格1,单击提交按钮后,它不会再次进入查询响应1,是否有更好的方法来做到这一点?

【问题讨论】:

  • 您可以使用 rxjs 主题来管理 div 的状态以及在组件之间传递数据。使用这些状态,您可以显示或隐藏您的 div
  • 这就是我现在正在做的事情吗?或者你有更好的方法?
  • 请立即检查您的 stackbliz
  • 你叉了我的 stackblitz 吗?

标签: javascript angular typescript rxjs subject


【解决方案1】:

inquiry-store.service.ts

public formState = new Subject<boolean>();
public responseState = new Subject<boolean>();

inquiry-form.component.ts

isHasSummon = false;

ngOnInit() {
    this.inqueryStore.formState.subscribe(res => {this.isHasSummon = res});
}

onSubmit() {
    this.isHasSummon = true;
    this.inqueryStore.responseState.next(true);
}

inquiry-response.component.ts

isShowResponse = false;

ngOnInit() {
    this.inqueryStore.responseState.subscribe(res => {this.isShowResponse = res});
}

goToInquiryForm() {
    this.isShowResponse = false;
    this.inqueryStore.formState.next(true);
}

试试这个。您可以使用相同的模式来显示和隐藏您的摘要部分

我为此创建了两个新的公共主题。但这不是强制性的。您使用了很好的方法来封装主题。你可以使用这种方式,我这样做只是为了简单。希望这会奏效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-02
    • 1970-01-01
    • 1970-01-01
    • 2016-07-09
    • 2019-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多