如何用新的 observable 替换 http observable?
How to replace http observable with new observable?
我认为我根本不理解 rxjs observables 的概念 angular 2.
我创建了一个其他人可以订阅并获取 http 调用结果数据的可观察对象 属性。
如果我想发出另一个 http 请求,可能需要修改一些参数以拉回一些新数据,我该怎么办?我只是用这个新的 observable 替换 observable 吗?这会破坏我的订阅组件对之前的可观察对象的订阅吗?
免责声明:我没有使用过 angular2,但我确实经常使用 RxJS。
我可以说,通常情况是对于像 http 请求这样的单次事件,生成的 Observable 只会从该请求中获得一个结果。如果您想发出更多请求,则需要再次调用该方法。即
$http.get('/people.json').map(res => res.json()).subscribe(people => this.people = people);
现在,如果您计划发出多个后续请求,那么通常您会通过其他事件触发调用,可能是用户事件或网络事件,您甚至可以将其设置为 运行 每对秒。如果不是 "break the chain",您需要使用 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);
我认为我根本不理解 rxjs observables 的概念 angular 2.
我创建了一个其他人可以订阅并获取 http 调用结果数据的可观察对象 属性。
如果我想发出另一个 http 请求,可能需要修改一些参数以拉回一些新数据,我该怎么办?我只是用这个新的 observable 替换 observable 吗?这会破坏我的订阅组件对之前的可观察对象的订阅吗?
免责声明:我没有使用过 angular2,但我确实经常使用 RxJS。
我可以说,通常情况是对于像 http 请求这样的单次事件,生成的 Observable 只会从该请求中获得一个结果。如果您想发出更多请求,则需要再次调用该方法。即
$http.get('/people.json').map(res => res.json()).subscribe(people => this.people = people);
现在,如果您计划发出多个后续请求,那么通常您会通过其他事件触发调用,可能是用户事件或网络事件,您甚至可以将其设置为 运行 每对秒。如果不是 "break the chain",您需要使用 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);