When you implement a search bar, the user can make several different queries in a row. With a Promise based implementation, the displayed result would be what the longest promise returns. This is the problem which we want to solve.

<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.rawgit.com/lodash/lodash/3.0.1/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/less.js/1.3.3/less.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/2.3.22/rx.all.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body ng-app="APP">
<div>
<p>Click on "Pets" then on "Nothing" in each form</p>
<p>Because pets' promise take long to resolve (longer than nothing's), it ends up with inconsistent output in Basic setup: nothing should be displayed but pets arrive!</p>
<p>RxJs is an elegant way to prevent this concurrency problems from appearing.</p>
</div>
<div ng-controller="StandardController as standard" style="margin-top:50px;">
<p>Basic setup</p>
<input id="s-pets" name="standardEntityType" type="radio" ng-model="standard.filters.entityType" value="pets">
<label for="s-pets">Pets</label> <input id="s-colors" name="standardEntityType" type="radio" ng-model="standard.filters.entityType" value="colors">
<label for="s-colors">Colors</label> <input id="s-nothing" name="standardEntityType" type="radio" ng-model="standard.filters.entityType" value="nothing">
<label for="s-nothing">Nothing</label> <p>
{{ standard.filters | json }}
</p>
<ul>
<li ng-repeat="entity in standard.entities">
{{ entity.name }}
</li>
</ul>
</div>
</body>
</html>
console.clear();

angular.module('APP', [])

.service('dataService', function($q, $timeout, $rootScope){
var colors = [
{ name: 'red' },
{ name: 'blue' },
{ name: 'white' }
]; var pets = [
{ name: 'cat' },
{ name: 'dog' }
]; function fakeAjax(returnValue, delay){
return $q(function(resolve){
$timeout(function() {
resolve(returnValue);
}, delay);
});
} function getColors(){
return fakeAjax(colors, 1500);
} function getPets(){
return fakeAjax(pets, 3000);
} function nullResponse(){
return fakeAjax([], 1);
} var mapping = {
colors: getColors,
pets: getPets
}; return {
getEntities: function(type){
if (mapping[type])
return mapping[type]();
else
return nullResponse();
}
};
}) .controller('StandardController', function($scope, dataService){
this.entities = [];
this.filters = {};
var controller = this; function searchEntities(type){
dataService.getEntities(type)
.then(function(entities){
controller.entities = entities;
});
} $scope.$watch(function(){
return controller.filters.entityType;
}, function(newVal){
searchEntities(newVal);
});
});

Solution 1: Add lodash _.debounce method to add some delay.

.controller('StandardController', function($scope, dataService){
this.entities = [];
this.filters = {};
var controller = this; function _searchEntities(type){
dataService.getEntities(type)
.then(function(entities){
controller.entities = entities;
});
} var searchEntities = _.debounce(_searchEntities, 1500);
$scope.$watch(function(){
return controller.filters.entityType;
}, function(newVal){
searchEntities(newVal);
});
});

The problem here is we have to assume a correct time. Too long, and the UI is not responsible enough, and too short, and we may encounter weirdness again.

Solution 2: Using RxJS

.controller('StandardController', function($scope, dataService){
this.entities = [];
this.filters = {};
var controller = this; var Observable = Rx.Observable;
var source = Observable.create(function(observe){
$scope.$watch(function(){
return controller.filters.entityType;
}, function(newType){
observe.onNext(newType);
});
}).flatMapLatest(function(type){
return Observable.fromPromise(dataService.getEntities(type));
}); var sub = source.subscribe(function(entities){
controller.entities = entities;
});
});

No matter what order we click the radio buttons, we'll always get the expected outcome. RxJS will handle that for us. The main benefit of RxJS over mere promises is we always get the latest query results. You can see, this implementation of Rx has a way to cancel promises.

Two methos to apply:

.controller('StandardController', function($scope, dataService){
this.entities = [];
this.filters = {};
var controller = this; var Observable = Rx.Observable;
var source = Observable.create(function(observe){
$scope.$watch(function(){
return controller.filters.entityType;
}, function(newType){
observe.onNext(newType);
});
}).debounce(500).flatMapLatest(function(type){
return Observable.fromPromise(dataService.getEntities(type));
}); var sub = source.subscribe(function(entities){
controller.entities = entities;
}); $scope.$on('destory', function(){
sub.dispose();
}); });

The first thing is to clean after yourself. On each destroy event on the scope, so basically, whenever you use a router, it could be on route change, you have to dispose the listener so Rx knows it can get rid of everything linked to it.

The second thing is we don't want to put too much pressure on our server, so we are going to use debounce again. It's very important to understand here that debounce is not a way to avoid UI issues. It's a way to avoid useless server queries.

[RxJS + AngularJS] Sync Requests with RxJS and Angular的更多相关文章

  1. Angular Multiple HTTP Requests with RxJS

    原文:https://coryrylan.com/blog/angular-multiple-http-requests-with-rxjs ----------------------------- ...

  2. [Vue-rx] Cache Remote Data Requests with RxJS and Vue.js

    A Promise invokes a function which stores a value that will be passed to a callback. So when you wra ...

  3. [AngularJS] Consistency between ui-router states and Angular directives

    ui-router's states and AngularJS directives have much in common. Let's explores the similarities bet ...

  4. [AngularJS 2 实践 一]My First Angular App

    最近一直在看关于AngularJS 2的资料,查看了网上和官网很多资料,接下来就根据官网教程步骤一步步搭建我的第一个Angular App AngularJS 2说明请参考:http://cnodej ...

  5. [RxJS] Refactoring Composable Streams in RxJS, switchMap()

    Refactoring streams in RxJS is mostly moving pieces of smaller streams around. This lessons demonstr ...

  6. [RxJS] Reactive Programming - Why choose RxJS?

    RxJS is super when dealing with the dynamic value. Let's see an example which not using RxJS: var a ...

  7. AngularJS进阶(二十五)requirejs + angular + angular-route 浅谈HTML5单页面架构

    requirejs + angular + angular-route 浅谈HTML5单页面架构 众所周知,现在移动Webapp越来越多,例如天猫.京东.国美这些都是很好的例子.而在Webapp中,又 ...

  8. angularjs探秘<三> 控制器controller及angular项目结构

    先来看一个例子 <!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset=&quo ...

  9. AngularJS源码解析1:angular自启动过程

    angularJS加载进来后,会有一个立即执行函数调用,在源代码的最下面是angular初始化的地方.代码展示: bindJQuery(); publishExternalAPI(angular); ...

随机推荐

  1. Ext.Date 方法

    1.Ext.Date.add(date,interval,value); 提供执行基本日期运算的简便方法; date 日期对象, interval 一个有效的日期间隔枚举值, value 向当前日期上 ...

  2. Win7 下,离线安装 Android Studio 1.0.1 的方法

    此教程没有亲自动手试过,先保存在这里 http://download.csdn.net/detail/tuobaxiao2008/8268281

  3. Linux相关命令

    使用的是ubuntu 安装JDK   输入java 命令会有提示安装的软件列表 sudo apt-get install openjdk-6-jdk sudo rm file名 删除文件 sudo r ...

  4. "Invalid bound statement (not found): com.sitech.admin.dao.TbOpenAbilityInfoDao.findAbilityReadyUp"mybatis配置文件bug

    问题描述: 通常在正常启动某项工程后操作某个功能时抛出的bug: org.apache.ibatis.binding.BindingException: Invalid bound statement ...

  5. 转载:用Dreamweave cs 5.5+PhoneGap+Jquery Mobile搭建移动开发

    转载地址:http://blog.csdn.net/haha_mingg/article/details/7900221 移动设备应用开发有多难,只要学会HTML5+Javascript就可以.用Dr ...

  6. Girls' research

    hdu3294:http://acm.hdu.edu.cn/showproblem.php?pid=3294 题意:就是给你一个串,然后求一个最长的回文串,输出起点及串,但是这里在之前要转化一下. 题 ...

  7. 李洪强iOS开发之-环信01_iOS SDK 前的准备工作

    李洪强iOS开发之-环信01_iOS SDK 前的准备工作 1.1_注册环信开发者账号并创建后台应用 详细步骤:  注册并创建应用 注册环信开发者账号 第 1 步:在环信官网上点击“即时通讯云”,并点 ...

  8. jinfo命令(Java Configuration Info)

    jinfo可以输出并修改运行时的java 进程的opts.用处比较简单,用于输出JAVA系统参数及命令行参数.用法是jinfo -opt  pid 如:查看2788的MaxPerm大小可以用  jin ...

  9. hadoop-2.0.0-cdh4.2.1源码编译总结

    经过一个星期多的努力,这两个包的编译工作总算告一段落. 首先看一下这一篇文章: 在eclipse下编译hadoop2.0源码 http://www.cnblogs.com/meibenjin/arch ...

  10. python乱码处理

    在.py文件第一行加上以下任意一种,只是写法不同,效果一样的. # -*- coding: UTF-8 –*- #vim: set fileencoding=utf-8: # coding=utf-8 ...