angular 4 best practice: load global data via service and store it

7.4k Views Asked by At

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.

my service:

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<any>;

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 => res.json())
            .do((data) => {
              this.cachedData = data;
            })
        .share();
    }
  }

my component:

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<any[]>;
   constructor(private globalDataService: GlobalDataService) { }
   ngOnInit() {
      this.globalDataService.getData().subscribe(
        (resp) => {
            this.todos = resp;
        }
    );
}}

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.

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.

If you need more information, feel free to ask.

1

There are 1 best solutions below

0
On BEST ANSWER

Do you have the service provided multiple times? You should only register the service one time.

I see it in your Dashboard component:

providers: [GlobalDataService]

Do you have it listed like this in any other component or module?

To share a service, it should be registered one time only:

  • Either at the root of the component tree (such as app component)
  • OR in a module instead of a component.

If you register it multiple times, it will not work as a singleton and you won't get shared data.