根据另一个 non-related 组件 Angular 的下拉选择更改数据

Change data based on dropdown selection from another non-related component Angular

我有 non-related 个组件。当我更改公司时,从 header 组件中,我需要显示与我从 header 组件中 select 编辑的公司匹配的数据。目前,当我在另一个页面时它正在工作并且一旦访问该页面它就会改变但是当我 select 来自 header 的一家公司时我需要及时改变它。

Header.ts

  companyData: Company;
  companyId;

  getCompany() {
    this.companyService.getCompanies().subscribe(x =>
      this.companyData = x
    );
  }

  changeCompany(companyId) {
    this.systemFunction.changeCompany(companyId);
  } 

普通service.ts

  private companySource = new BehaviorSubject('');
  currentCompany = this.companySource.asObservable(); 

  changeCompany(companyId: number) {
    this.companySource.next(String(companyId));
  } 

Branch.ts

  ngOnInit() {
    this.systemFunction.currentCompany.subscribe(cid => this.companyId = cid);
   this.systemFunction.changeCompany(this.companyId);
  }

  ngAfterViewInit() {
    this.getBranches();
  }

  getBranches() {
    this.branchService.getBranches().subscribe(b => {
      Object.assign(this.branchData, b);
      // tslint:disable-next-line:no-shadowed-variable
      this.branchData = this.branchData.filter(b => b.CompanyId == this.companyId);
    });
  } 

我相信您希望您的 branchData 在更改 companyId 后重新评估?但是你的分支是它自己的订阅机制的一部分,所以一旦 getBranches() 订阅被触发 - 你就会得到结果。

或者您需要直接对公司变更做出反应,并在变更后更新您的分支机构,例如

ngOnInit() {
   this.systemFunction.currentCompany.subscribe(cid => refreshCompany(cid));
   this.systemFunction.changeCompany(this.companyId);
  }

  ngAfterViewInit() {
    this.getBranches();
  }

  getBranches() {
    this.branchService.getBranches().subscribe(b => {
       this.branchData = ...;
       this.refreshBranches();
    });
  }

  refreshCompany(cid) {
    this.companyId = cid;
    this.refreshBranches();
  }

  refreshBranches() {
    this.filtered = this.companyId ? 
       this.branchData.filter(b => b.CompanyId == this.companyId) : [...this.branchData];
  }

如果我的实现正确,currentCompany 就像一个主题。至少你订阅了它。

所以您也可以将分支的刷新调用也放入此订阅中。

this.systemFunction.currentCompany.subscribe(cid => {
    this.companyId = cid;
    this.getBranches();
});

您最终可能会在初始化时不必要地额外加载分支。如果是这样,您可以删除 afterViewInit 中的 getBranches 调用。