如何用新的observable替换http observable?

时间:2016-02-02 00:22:02

标签: angular observable rxjs

我认为我从根本上不理解角度为2的rxjs observables的概念。

我创建了一个可观察的属性,其他人可以订阅并获取http调用结果的数据。

如果我想制作另一个http请求,或者使用一些修改后的参数来撤回一些新数据,我该怎么办?我只是用这个新的observable替换observable吗?这是否会破坏我的订阅组件对之前的observable的订阅?

1 个答案:

答案 0 :(得分:4)

免责声明:我没有使用过angular2,但我确实经常使用RxJS。

我可以说,通常情况下,对于像http请求这样的单一事物,Observable生成的只会从该请求获得一个结果。如果您想要提出更多请求,则需要再次调用该方法。即。

From the docs

$http.get('/people.json').map(res => res.json()).subscribe(people => this.people = people);

现在,如果您计划发出多个后续请求,那么通常您将使用其他一些事件(可能是用户事件或网络事件)触发呼叫,您甚至可以将其设置为每隔几秒定期运行一次。为了不“破坏链条”,您需要使用flatMap之一(基本上是.map().merge())变体将结果展平为单个链。

例如,如果你有一个任意的事件(注意语法可能会有所不同,因为那里有几个版本的RxJS):

Rx.Observable.fromEvent($someButton, 'click')
             //Gather the parameters for the request
             .map(e => {id : 'abc123'})
             //Flatten each request into a single stream so the observer
             //never knows the difference 
             .flatMap(params => $http.get(`/people/${params.id}`), 
                      (params, res) => res.json())
             //Do your update here
             .subscribe(person => this.people[person.id] = person);