JockelzF
JockelzF

Reputation: 423

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:

  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

Answers (3)

Mahdi Fazeli
Mahdi Fazeli

Reputation: 21

You can use the following code. Works well.

  ngOnInit() {
        this.dataService.getDataStream().subscribe(
        res => {
        this.somethingsomething = res ;
            console.log(res);
          });     
      } 

Upvotes: 2

JoshSommer
JoshSommer

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

eko
eko

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 somethingsomethings value also changes. This is because Objects are mutable in javascript.

If getDataStream was returning a response from a server, that wouldn't be the case.

Upvotes: 0

Related Questions