Angular让前端飞RxJS

输入提示(type-ahead)建议

2018-06-06  本文已影响3人  readilen

可观察对象可以简化输入提示建议的实现方式。典型的输入提示要完成一系列独立的任务:

完全用 JavaScript 的传统写法实现这个功能可能需要大量的工作。使用可观察对象,你可以使用这样一个 RxJS 操作符的简单序列:

import { Component, AfterViewInit } from '@angular/core';
import { fromEvent } from 'rxjs';
import { ajax } from 'rxjs/ajax'
import { debounce, map, filter, debounceTime, distinctUntilChanged, switchMap} from 'rxjs/operators'


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit{
  title = 'My frist Angular App!';
  searchBox;
  typehead;
  constructor(){
  
  }

  ngAfterViewInit(){
    this.searchBox = document.getElementById('food');
    this.typehead = fromEvent(this.searchBox, 'input').pipe(
      map((e: KeyboardEvent) => e.target.value),
      filter(text => text.length > 2),
      debounceTime(250),
      distinctUntilChanged(),
      // switchMap(() => ajax('/api/endpoint'))
    );
    this.typehead.subscribe(data => {
      console.log(data);
    });  
  }
}

几点注意事项,

上一篇下一篇

猜你喜欢

热点阅读