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

Time:09-23

I have non-related components. From the header component when I change company I need to show data match with the company which I selected from the header component. currently, it's working when I in another page and once visit that page it changes but I need to change it on time when I select a company from the header.

Header.ts

  companyData: Company;
  companyId;

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

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

common 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);
    });
  } 

CodePudding user response:

I believe you expect your branchData to be re-evaluated after changing companyId? But your branches are part of its own subscription mechanism, so once getBranches() subscription will be fired - you will get result.

Or you need to react to company change directly and update your branches once changed as well, e.g.

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];
  }

CodePudding user response:

If I got your implementation right, currentCompany is something like a subject. At least you are subscribing to it.

So you could put the refresh call for the branches into this subscription as well.

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

You might end up with an unnecessary additional loading of the branches on initialisazion. If so, you could just remove the getBranches call in your afterViewInit.

  • Related