Angular HTTP调用已订阅一个主题,从而关闭了该主题 [英] Angular HTTP call subscribed to a subject closing the subject
问题描述
我有两个可以获取给定对象的服务:初始HTTP调用以获取完整列表,以及websocket通知以实时更新新元素.
I have two services that can fetch a given object : an initial HTTP call to get the full list, and websocket notification to have live update of new elements.
我想将两个呼叫连接到相同的可观察对象,以便显示页面不了解后端.
I want to wire the two calls to the same observable so the display page has no knowledge of the backend.
有打电话的消息:
private getInitialData(subject: Subject<any>) {
this._http.get<Array<any[]>>(`/call/to/backend`)
.flatMap(items => items)
.subscribe(subject);
}
private listenNewData(subject: Subject<any>) {
this.websocketService.listen('/some/ws/topic')
.subscribe(subject);
}
private initialize() {
const subject = new Subject<any>();
this.dataService.getInitialData(subject);
this.listenNewData(subject);
subject.subscribe(item => this.items.push(item))
}
以这种方式注册主题时,似乎该主题实际上是在HTTP解析后关闭的,并且没有websocket通知发送给该主题.
When registering this way the subject it seems the subject is actually closed after the HTTP resolution, and no websocket notification get sent to the subject.
但是,在订阅函数上使用回调注册时:
However, when registering using callbacks on subscribes functions :
private getInitialData(subject: Subject<any>) {
this._http.get<Array<any[]>>(`/call/to/backend`)
.flatMap(items => items)
.subscribe(item => subject.next(item));
}
private listenNewData(subject: Subject<any>) {
this.websocketService.listen('/some/ws/topic')
.subscribe(item => subject.next(item));
}
我没有问题,所有物品都已正确提取.
I have no issues and all items are correctly fetched.
我想知道两个版本为何不同,为什么在第一种情况下,主题最终封闭.
I wanted to know why the two versions are different, and why, in the first case, the subject end up closed.
感谢您的帮助.
推荐答案
这是正确的行为.当您使用 .subscribe(subject)
时,您将同时订阅所有三种类型的通知.所有主题都是观察者,因此与编写以下内容相同:
This is correct behavior. When you use .subscribe(subject)
you're subscribing to all three types of notifications. All Subjects are observers so it's the same as writing the following:
.subscribe(
v => subject.next(v),
err => subject.error(err),
() => subject.complete()
);
因此,如果仅使用 .subscribe(item => subject.next(item))
,则仅传递 next
通知,而不会传递错误
或 complete
通知,因此 subject
永远不会完成.
So if you use just .subscribe(item => subject.next(item))
you're passing only the next
notifications and no error
or complete
notifications so subject
is never completed.
这篇关于Angular HTTP调用已订阅一个主题,从而关闭了该主题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!