typescript – 使用observable跟踪typeahead列表中的当前位置

前端之家收集整理的这篇文章主要介绍了typescript – 使用observable跟踪typeahead列表中的当前位置前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用TypeScript自动完成组件(对于Angular 2,虽然这不是问题的核心),我想通过RxJs(5.0.0-beta.8)中的observable来管理它的大部分(或全部).通过向上/向下箭头键操作时,我在跟踪建议列表中的当前项目位置时遇到问题:索引仍然停留在0.

@H_502_8@

所有以下逻辑都留在一个单独的类中,该类接收输入的observable并生成订阅输出observable(这就是为什么与Angular 2没有严格关系).客户端代码订阅正确输出observable.@H_502_8@

这是一些代码:@H_502_8@

@H_502_8@

// Component responsible for managing only the list of suggestions
// It receives inputs from text field and it produces outputs 
// as current index in list,when to hide list,etc.
class AutocompleteListDriver {
  currentIndex$: Observable<number>;
  doClose$: Observable<void>;
  // ...

  constructor(...
    matches$: Observable<string[]>,// list of suggestions matching text in field
    keyUp$: Observable<KeyboardEvent>,// keyup events from text field
    keyDown$: Observable<KeyboardEvent>,// keydown events from text field
    ...) {

    const safeMatches$= matches$
      .startWith([]);  // start with a clear,known state internally

    // when list is empty,component is hidden at rest:
    // detect keys only when component is visible
    const isActive$= safeMatches$
      .map(matches => matches.length !== 0);

    const activeKeyUp$= keyUp$
      .withLatestFrom(isActive$)
      .filter(tuple => tuple[1]) // -> isActive
      .map(tuple => tuple[0]);   // -> keyboardEvent

    this.currentIndex$= safeMatches$
      .switchMap(matches => {
        const length = matches.length;
        console.log('length: ' + length);

        const initialIndex = 0;

        const arrowUpIndexChange$= activeKeyUp$
          .filter(isArrowUpKey)
          .map(_ => -1);

        const arrowDownIndexChange$= activeKeyUp$
          .filter(isArrowDownKey)
          .map(_ => +1);

        const arrowKeyIndexChange$= Observable
          .merge(arrowUpIndexChange$,arrowDownIndexChange$)
          .do(value => console.log('arrow change: ' + value));

        const arrowKeyIndex$= arrowKeyIndexChange$
          .scan((acc,change) => {
            // always bound result between 0 and length - 1
            const index = limitPositive(acc + change,length);

            return index;

          },initialIndex)
          .do(value => console.log('arrow key index: ' + value))
          .startWith(0);

        return arrowKeyIndex$;
      })
      .do(value => console.log('index: ' + value))
      .share();
  }
}

这个想法是每次发出一个新的匹配(建议)列表时,列表中的当前索引应该开始一个新的“序列”,所以说.这些序列中的每一个从0开始,由于向下/向上箭头键而监听增量/减量,通过注意不要超出下限/上限来累积它们.@H_502_8@

要向我开始一个新序列,它会转换为switchMap.但是使用这样的代码,控制台只显示:@H_502_8@

@H_502_8@

length: 5
index: 0

根本没有检测到箭头向上/向下键(尝试在arrowDownIndexChange $上插入其他日志),因此不再有日志,也不会影响最终组件.就好像他们的observable不再被订阅,但据我所知,switchMap应该订阅最新生成的序列并删除/取消订阅以前的所有序列.@H_502_8@

只是为了尝试,我使用了mergeMap:在这种情况下,检测到箭头键,但当然问题是所有序列(由于匹配时的前一时刻)被合并在一起并且它们的值彼此重叠.除了这个不正确之外,匹配列表有时会变空,所以总是有一个点,当前索引序列始终保持为0.这个序列与所有其他序列合并并重叠,给出索引的最终结果0.@H_502_8@

我究竟做错了什么?@H_502_8@

解决方法

好.显然我以前的调查结果通过rxjs docs出错了(当然我在写完问题后得到了这个,然后寻找更多的见解).

@H_502_8@

似乎switchMap不适合这种情况.我应该使用的是switch().这不应该是一个惊喜,来自.Net Reactive Extensions背景……但我不知道为什么语言之间的命名变化经常让我错了.@H_502_8@

工作解决方案应该是:@H_502_8@

@H_502_8@

this.currentIndex$= safeMatches$
  // use map to generate an "observable of observables"
  // (so called higher-order observable)
  .map(matches => {
    const length = matches.length;
    // ...
  })
  // "unwrap" higher order observable,by always 
  // keeping subscribed to the latest inner observable
  .switch()
  .do(value => console.log('index: ' + value))

编辑
这还不够.我还必须放弃activeKeyUp $,而不是原始的keyUp $.@H_502_8@

如果有人有其他建议(或对当前行为的解释,例如activeKeyUp / keyUp),请随时回答.@H_502_8@

编辑#2感谢@paulpdaniels评论:事实证明,唯一真正的问题是activeKeyUp $Vs keyUp $bug.用switchMap()替换map().switch()并没有以任何方式损害功能.@H_502_8@

猜你在找的Angularjs相关文章