zoukankan      html  css  js  c++  java
  • [AngularJS + RxJS] Search with RxJS

    When doing search function, you always need to consider about the concurrent requests. 

    AEvent ----(6s)---> AResult

    ------(100ms)-------

    BEvent -----(1s)---> BResult

    It means A event needs to take 6 seconds to get the result, but B only need 1 second, in the between there is 100ms. 

    So B result will appear on the DOM first, but later will be overwritten by A result once A finished. 

    To overcome this problem, we can use RxJS:

    class HelpSearchCtrl {
        constructor(HelpSearchService, $scope, $log) {
            this.HelpSearchService = HelpSearchService; 
            this.searchTerm = null;
            this.$log = $log;
            this.$scope = $scope;
    
            let listener = Rx.Observable.create( (observe)=>{
               
                 this.$scope.$watch( ()=>{
                    return this.searchTerm;
                 }, ()=>{
                     observe.onNext(this.searchTerm);
                 })
            })
            .debounce(500)
            .flatMapLatest( (searchTerm)=> {
                return Rx.Observable.fromPromise(this.doSearch(searchTerm));
            }).subscribe();
    
            this.$scope.$on('$destory', ()=>{
                this.$log.debug('cancelled!');
                listener.dispose();
            })
        } 
    
        doSearch(searchTerm) {
            return this.HelpSearchService.searchForContent(searchTerm);
        }
    }
    
    const clmHelpSearchDirective = () => {
        return {
            restrict: 'EA',
            scope: {},
            replace: true,
            template: require('./help-search.html'),
            controller: HelpSearchCtrl,
            controllerAs: 'vm',
            bindToController: true
        }
    };
    
    export default (ngModule)=> {
        ngModule.directive('clmHelpSearch', clmHelpSearchDirective);
    }
  • 相关阅读:
    AJAX以及XMLHttpRequest
    理解Promise对象
    HTTP报文整理
    前端 — URL、URI、URN概念和区别整理,以及URL语法规则
    gulp与webpack的区别
    Sass和less的区别是什么?用哪个好
    Vue3.0 && Vue3.0初体验 一
    Promise入门详解和基本用法
    js对象方法大全
    hash模式和history模式 实现原理及区别
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5185266.html
Copyright © 2011-2022 走看看