Reputation: 423
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:
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.
How can I console.log the data whenever it changes?
Upvotes: 1
Views: 12030
Reputation: 21
You can use the following code. Works well.
ngOnInit() {
this.dataService.getDataStream().subscribe(
res => {
this.somethingsomething = res ;
console.log(res);
});
}
Upvotes: 2
Reputation: 2618
To log this data to the console it's best to use the do
operator. Every time a new value is pushed from the getDataStream
observable the do
operator will console.log that data.
private somethingsomething;
ngOnInit() {
this.dataService.getDataStream()
.do(data => console.log(data))
.subscribe((data) => {
this.somethingsomething = data;
}
)
}
Upvotes: 0
Reputation: 40647
The reason this.somethingsomething
changes is that it has the reference of someData
. getDataStream
method gets executed only once. But since the object changes, the field with that reference somethingsomething
s value also changes. This is because Object
s are mutable in javascript.
If getDataStream
was returning a response from a server, that wouldn't be the case.
Upvotes: 0