1
votes

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?

3
depends on how you are using it in the view. Can you provide some information on that? - Nehal

3 Answers

0
votes

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.

0
votes

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;
      }
    )
  }
0
votes

You can use the following code. Works well.

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