在rxjs中取消对新Emmision的Ajax请求

non*_*hto 1 reactive-programming rxjs

我是反应式编程的新手,在创建AJAX导航侧导航时遇到问题。

<ul>
    <li>change_password</li>
    <li>update_profile</li>
</ul>
<h3> The result </h3>
<div id="theContent"></div>

<script type="text/javascript">
var listClick$ = Rx.Observable.create(function(observer){

            $('li').click(function(){

                let pageName = $(this).html();    
                observer.next(pageName);

            });

        }).startWith('change_password').flatMap(function(pageName){

            return Rx.Observable.fromPromise($.getJSON('http://localhost:3000/settings/'+pageName));        
        });
listClick$.subscribe(function(gottenJson){

$('#theContent').html(gottenJson.page);
}); 
</script>
Run Code Online (Sandbox Code Playgroud)

当我单击change_password或update_profile时,发出了ajax请求,但change_password的请求被延迟,因此,当单击它,然后单击update_profile时,将显示update_profile表单,但在完成时将被change_password表单替换。

单击另一个列表项时,如何取消第一个AJAX请求?

Mar*_*ten 6

switchMap生成新的发射时,可以使用哪个从上一个流(您的Ajax调用)中取消订阅。

话虽如此; 因为您使用的是Promise Ajax版本,所以无法取消该请求。因此,即使switchMap提供了cancel(unsubscribe)挂钩,promise也不会对此起作用。

您可以使用Rx.Observable.ajax可观察的版本。在您取消订阅之前,该呼叫可以被中止。据我所知它依赖于DOM所以在环境的NodeJS可以使用通用的Ajax NPM包取代了内部xhrxhr2在非DOM ENV运行时,从故宫。