#Storing reference to data from service on the component

7 messages · Page 1 of 1 (latest)

sinful eagle
#

Keep in mind that mutations will be reflected, but reference changings will not.

tacit oasis
#

When you say reference changings, do you mean redefining this.dataObj to be a different object? eg:

fetchSomeNewData() {
  this.http.get('some url').suscribe(newObj => {
    this.dataObj = newObj;
  });
}
sinful eagle
#

Assuming that's inside the service, yes.

tacit oasis
#

Yeah I guess that could be seen as a valid use case if your expecting to only use that data from the service temporarily. But even then I think a getter would be safer:

private _newDataObj;

get dataObj() {
  return this._newDataObj || this.service.dataObj;
}

fetchSomeNewData() {
  // fetch the data and set it to this._newDataObj;
}
sinful eagle
#

Why not exposing an observable as everyone else does?

tacit oasis
#

So basically the same thing, except for using observables and pipe? Or am I misunderstanding what you are suggesting?

sinful eagle
#

The getter is not different than accessing the data.
To get a fresh copy of th evalue you should call it explicitly.
With Observable you leverage a "Push" pattern, where the component will be notified of a new value without you having to poll for it.