totoro
totoro

Reputation: 3407

data sharing approaches in Angular 2

A question on data sharing among various components in an Angular 2 app. Currently the structure of my app resembles that of this one in the tutorial, where Angular bootstraps the AppComponent and multiple components are routed from there. two questions:

  1. In this case, is AppComponent the "parent" of the other 2 components (namely Dashboard and Heroes as in the tutorial)? If so, is it good idea to store all the data as variables inside AppComponent, and then pass data to its children as necessary?

  2. Or, is it better to get all the data via http and cache them inside Service? Why?

Thank you!

Upvotes: 1

Views: 75

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202306

From my point of view caching data into services is better since it's transparent for your application. Moreover the asynchronous processing is hidden. Here is a sample:

export class SharedService {
  constructor(private http:Http) {
  }

  getData() {
    if (this.cachedData) {
      return Observable.of(this.cachedData);
    } else {
      return this.http.get(...)
            .map(res => res.json())
            .do((data) => {
              this.cachedData = data;
            });
    }
  }
}

One point you need to be careful with the other approach is when data are ready to be provided to sub components.

But it depends on your use case.

Upvotes: 2

Related Questions