title: angular 4 best practice: load global data via service and store it
body: <p>i want to build an angular 4 application, where i can search for user from a database and use the information of the person i found on different routes. my problem at the moment is, if i load some data via a service, change the route and come back, the data gets loaded again.</p>
  
  <p><strong>my service:</strong></p>
  
  <pre><code>import { Injectable } from '@angular/core';
  import { Http } from '@angular/http';
  import { Observable } from 'rxjs/Observable';
  import 'rxjs/add/operator/map';
  import 'rxjs/add/operator/do';
  
  @Injectable()
  export class GlobalDataService {
  cachedData: Observable&lt;any&gt;;
  
  getData() {
      if (this.cachedData) {
        console.log('cache data found');
        return Observable.of(this.cachedData);
      } else {
        console.log('cache data NOT found');
        return this.http.get('https://56e05c3213da80110013eba3.mockapi.io/api/todos')
              .map(res =&gt; res.json())
              .do((data) =&gt; {
                this.cachedData = data;
              })
          .share();
      }
    }
  </code></pre>
  
  <p><strong>my component:</strong></p>
  
  <pre><code>import { Component, OnInit } from '@angular/core';
  import { FormBuilder, Validators} from '@angular/forms';
  import { Http } from '@angular/http';
  import { Observable } from 'rxjs';
  import 'rxjs/add/operator/mergeMap';
  import 'rxjs/add/operator/map';
  import { GlobalDataService } from '../../services/global-data.service';
  @Component({
     selector: 'app-dashboard',
     templateUrl: './dashboard.component.html',
     styleUrls: ['./dashboard.component.css'],
     providers: [GlobalDataService]
  })
  export class DashboardComponent implements OnInit {
     todos: Observable&lt;any[]&gt;;
     constructor(private globalDataService: GlobalDataService) { }
     ngOnInit() {
        this.globalDataService.getData().subscribe(
          (resp) =&gt; {
              this.todos = resp;
          }
      );
  }}
  </code></pre>
  
  <p>when i run the app, i get the console.log 'NOT found' and the data gets loaded, as its supposed to be, but when i change the route and switch back, its get loaded again which is not correct.</p>
  
  <p>I hope you can help me with maybe a full working example, so i could have a look at the code. maybe i'm missing something.</p>
  
  <p>If you need more information, feel free to ask.</p>