简体   繁体   中英

Angular2 update value from http request

I have a simple service does a few get requests:

getDevices() {
  return this.http.get('https://api.particle.io/v1/devices')
    .map((response: Response) => response.json());
}

getVariable(deviceId: string) {
  return this.http.get('https://api.particle.io/v1/devices/' + deviceId + '/running')
    .map((response: Response) => response.json());
}

In my component I have the following function which fetches devices and adds the variable from getVariable to each device in this.devices.

  getDevicesAndRunning() {
    function callback(array, data, res) {
      array.push(Object.assign(data, {"running": res.result}))
    }
    this.photonService.getDevices()
      .subscribe(
        data => {
          const myArray = [];
          for (var i=0; i<data.length; i++) {

            if (data[i].connected) {
              console.log(data, i);
              this.photonService.getVariable(data[i].id)
                .subscribe(
                  callback.bind(this, myArray, data[i])
                );
            };
          }
          this.devices = myArray;
        }
      );
  }

I can then call getDevicesAndRunning() to update the list of devices and iterate over them in the view. Currently I'm doing this in OnInit and whenever the user clicks a button. However, since this.devices gets repopulated each time the function is called the user sees a blank list for however long the request takes to respond. All I want is for the res.result to be updated, not the entire array.

Since you are bulk updating the list you are blanking it out while the refresh is happening. You will need to preserve the array and alter it on the fly. Splice out the removed items and push in the new ones. Let the sort function angular provides do the rest of the work.

I do this sort of thing by not using the originally returned list. I implemented something like this for an app that's in production now and it works great.

When you get the original list, stash it off to the side. Create a copy and use that for the display.

When you need to update it, get the new list, copy it, and now you have a lot of options; old vs. new, replace old, combine old and new, display delta, etc. There's some nice ES6 functions, not native but simple enough, out there to do things like unions, diffs, etc, and of course lodash will serve.

True, this involves a copy of the list, but in the app I built I dealt with thousands of objects and at least six lists simultaneously and never had any problems with memory etc. You just have to remember to clean it up if necessary.

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