简体   繁体   中英

two different arrays from the same API call updating each other

I have a weird situation. I have two objects:

sessionBase: ISessionViewWrapperModel = <ISessionViewWrapperModel>{};
sessionDisplay: ISessionViewWrapperModel = <ISessionViewWrapperModel>{};

I make an api call and populate both:

    this.appService.getCourtSessionWithHearings(Number(this.apiUser?.Id), this.sessionId).subscribe((response) => {
      this.sessionDisplay = response;
      this.sessionBase = response;
    });

Then I have a toggle button that if "on", I filter the "hearings" array in the sessionDisplay object. If off, it resets the entire sessionDisplay object to the sessionBase object:

    if (event.checked) {
      this.sessionDisplay.Hearings = this.sessionDisplay.Hearings.filter(x => x.IsCancelled === false && x.IsContinuance === false && x.IsReset === false);
    } else {
      this.sessionDisplay = this.sessionBase;
    }

the weird thing is that once I filter the hearings array on the "sessionDisplay" object, the hearings on the "sessionBase" object are also filtered. The only way I can make it work is to do two separate calls to the api:

    this.appService.getCourtSessionWithHearings(Number(this.apiUser?.Id), this.sessionId).subscribe((response) => {
      this.sessionBase = response;
    });

    this.appService.getCourtSessionWithHearings(Number(this.apiUser?.Id), this.sessionId).subscribe((response) => {
      this.sessionDisplay = response;
    });

it is like the response from the api call is impacted by the filter.

Any ideas what I am doing wrong? Basically, I am trying to avoid a round-trip to the server by having the original object separate from the display object since filtering creates a new array and there is no way to reset it.

Hope that makes sense.

Based on the comment by derstauner, I found the solution. When making the api call I use Object.assign and it works.

    this.appService.getCourtSessionWithHearings(Number(this.apiUser?.Id), this.sessionId).subscribe((response) => {
      this.sessionBase = response;
      this.sessionDisplay =  Object.assign({}, response); 

    });

then in my toggle funtion I also use Object.assign:

  hideInactive(event: MatSlideToggleChange): void {
    if (event.checked) {
      this.sessionDisplay.Hearings = this.sessionDisplay.Hearings.filter(x => x.IsCancelled === false && x.IsContinuance === false && x.IsReset === false);
    } else {
      this.sessionDisplay = Object.assign({}, this.sessionBase);
    }
  }

Thanks for the tip!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM