【发布时间】:2018-12-21 11:19:51
【问题描述】:
我有一个简单的场景:
service.ts:
private showComposeBoxAction = new BehaviorSubject<boolean>(null);
showComposeBox = this.showComposeBoxAction.asObservable();
openComposeBox(event:boolean) {
console.log("in openComposeBox");
this.showComposeBoxAction.next(event);
}
组件.ts:
constructor(
private _service: Service,
) {
this.subscriptions.add(
this._mailingService.showComposeBox.subscribe(event => {
if (event) {
this.displayCompose = true;
console.log("showComposeBox displayCompose", this.displayCompose);
}
})
);
}
component2.ts:
showComposeBox() {
if (this.count === 0) {
this._service.openComposeBox(true);
}
}
我在 openComposeMsg() 中记录了一条消息。 我面临的问题是我第一次正确订阅 showComposeBox observable 但第二次订阅时即使没有调用 next 也是因为 msg "in openComposeBox" 没有登录到控制台。
无法理解 BehaviorSubject 的行为。 我做错了什么?
【问题讨论】:
-
你的服务是单例吗?
-
@JBNizet Hi 正在使用 BehaviorSubject。它保存当前数据并在订阅者订阅后立即传递给订阅者
-
@Simer 好吧,这就是 BehaviorSubject 的重点:它有一个当前值,每次订阅时,都会立即通知您当前值。如果这不是您想要的,那么您一开始就不应该使用 BehaviorSubject。
-
我应该使用主题吗?可能是。阅读文档。
-
是的。如果您在使用它记录的内容之前阅读它,您将节省周,从而更容易遵守截止日期。
标签: angular angular2-observables angular-observable