简体   繁体   English

在Angular2中修改Observable会导致行为引发火灾

[英]Modifying Observable in Angular2 Causes BehaviorSubject to Fire

In the following plunk when you click on the Select Market an Observable is populated with an array of data. 在下面的单击列表中,单击“可观察对象”时将填充一系列数据。 The first item is highlighted in yellow because it has a property set to selected. 第一项以黄色突出显示,因为它的属性设置为选中。 When focus is on the input box you can arrow down in the list. 当焦点位于输入框上时,您可以在列表中向下箭头。 The problem is the BehaviorSubject is firing and grabbing the list of data from the server each time. 问题在于BehaviorSubject每次都在触发并从服务器获取数据列表。 How can I modify the selected property without searchTerms BehaviorSubject firing each time? 如何在不每次触发searchTerms BehaviorSubject的情况下修改所选属性? the method searchInputArrowKeyPressed in the market-search.component.ts file is where the arrow keys are being handled. market-search.component.ts文件中的searchInputArrowKeyPressed方法是处理箭头键的位置。

public searchInputArrowKeyPressed(event): void {
    this.markets = this.markets
        .map((markets: Market[]) => {
            for(let market of markets) {
                if(market.selected) {
                    if(event === 'down' && markets.indexOf(market) < markets.length) {
                        markets[markets.indexOf(market) + 1].selected = true;
                    }
                    if(event === 'up' && markets.indexOf(market) > 0) {
                        markets[markets.indexOf(market) - 1].selected = true;
                    }
                    market.selected = false;
                    return markets;
                }
            }
        });
}

https://plnkr.co/edit/TBYb5QBau9Vmz8PqQpCl?p=preview https://plnkr.co/edit/TBYb5QBau9Vmz8PqQpCl?p=preview

Thank you in advance for any and all help! 预先感谢您提供的所有帮助!

I agree with @n00dl3, reassigning the stream looks unnatural. 我同意@ n00dl3,重新分配流看起来很不自然。 I've modified your plunker so that every event (data, search, up/down and enter) has it's own stream. 我已经修改了您的插件,以便每个事件(数据,搜索,向上/向下和回车)都有自己的流。 Eg: 例如:

public searchInputArrowKeyPressed(event): void {
    this.upDownEvents.next(event);
}

Modification to the data is done through pushing updated array in data stream. 通过在数据流中推送更新的数组来完成对数据的修改。

    this.upDownEvents
      .withLatestFrom(this.markets)
      .subscribe(([event, markets]) => {
          for(let market of markets) {
              if(market.selected) {
                  // change selected

                  this.markets.next(markets);
                  return;
              }
          }
      });

Please, look here 请看这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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