我使用共享服务在两个独立组件之间传递数据。当我在共享服务中使用主题时,我无法在订阅组件的html中看到订阅的数据,但订阅后可以在控制台中看到它。而如果我使用Behaviorsubject,效果很好。谁能给我解释一下原因。
共享服务.ts:
//code with subject (not working)
private msgStatistics = new Subject<any>();
msgStatistics$ = this.msgStatistics.asObservable();
msgStats(message) {
this.msgStatistics.next(message)
}
//code with BehaviorSubject (working)
private msgStatistics = new BehaviorSubject<Object>(null);
msgStatistics$ = this.msgStatistics.asObservable();
msgStats(message) {
this.msgStatistics.next(message)
}
Run Code Online (Sandbox Code Playgroud)
组件2.ts:
this.shared_service.msgStatistics$.subscribe(res => {
this.message = res
console.log(this.message)
})
Run Code Online (Sandbox Code Playgroud)
上面的控制台在这两种情况下都会打印消息的值,但它不会以 html 形式呈现主题。