[英]How to console log data from observable subscription?
I have a simple function, included in a service, returning an observable of an object:我有一个简单的函数,包含在一个服务中,返回一个对象的可观察对象:
private someData;
getDataStream(): Observable<any> {
return Observable.of(this.someData);
}
I subscribe to this function onInit of a component:我订阅了一个组件的 onInit 函数:
private somethingsomething;
ngOnInit() {
this.dataService.getDataStream().subscribe(
(data) => {
this.somethingsomething = data; // WORKS AND ALWAYS UP TO DATE
console.log(data); // ONLY WORKS ONCE
}
)
}
As commented, the data when given to a variable, which is then displayed in the view, is always fine.正如所评论的那样,将数据提供给变量然后显示在视图中总是没问题的。 But the console.log on the other hand is only triggered once, and then never again.
但另一方面,console.log 只触发一次,然后再也不会。
How can I console.log the data whenever it changes?我如何在数据发生变化时 console.log ?
You can use the following code.您可以使用以下代码。 Works well.
效果很好。
ngOnInit() {
this.dataService.getDataStream().subscribe(
res => {
this.somethingsomething = res ;
console.log(res);
});
}
The reason this.somethingsomething
changes is that it has the reference of someData
. this.somethingsomething
改变的原因是它有someData
的引用。 getDataStream
method gets executed only once. getDataStream
方法只执行一次。 But since the object changes, the field with that reference somethingsomething
s value also changes.但是由于对象发生变化,具有该引用
somethingsomething
值的字段也会发生变化。 This is because Object
s are mutable in javascript.这是因为
Object
在 javascript 中是可变的。
If getDataStream
was returning a response from a server, that wouldn't be the case.如果
getDataStream
从服务器返回响应,则情况并非如此。
To log this data to the console it's best to use the do
operator.要将此数据记录到控制台,最好使用
do
运算符。 Every time a new value is pushed from the getDataStream
observable the do
operator will console.log that data.每次从
getDataStream
可观察对象推送新值时, do
运算符都会控制台记录该数据。
private somethingsomething;
ngOnInit() {
this.dataService.getDataStream()
.do(data => console.log(data))
.subscribe((data) => {
this.somethingsomething = data;
}
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.