Use BehaviorSubject in your service. It is already split, and it will give new subscribers the current value (so this does caching for you):
import {Injectable} from '@angular/core'; import {Http} from '@angular/http'; import {BehaviorSubject} from 'rxjs/BehaviorSubject'; import {settingsModel} from 'settingsModel'; @Injectable() export class MyService { private _settingsSource = new BehaviorSubject<settingsModel>(null); settings$ = this._settingsSource.asObservable(); constructor(private _http:Http) { this._http.get('./settings.json') .subscribe(response => { //console.log('response', response) this._settingsSource.next(response.json()) }); } }
Then use the observables in the template using asyncPipe or extract the data into a compound variable:
this.settings$ = this._myService.settings$; // use with asyncPipe this._myService.settings$.subscribe(data => this.settings = data);
Plunker
In Plunker, I have a child component that waits 4 seconds and then subscribe() s to show that the last / current value is actually retrieved. Plunker also demonstrates the use of asyncPipe.
source share