Angular2 global variable observable

I'm new to angular2, and I'm kinda stuck on something.

I created a global settings.service. This service retrieves settings from the API and populates the settings model with the collected data.

Service:

public settings : settingsModel; constructor(public http: Http){ this.setSettings() .subscribe( (data) => { this.settings = data }); } setSettings() : Observable<any>{ return : this.http.get('/settings') .map(response => response.json()); } getSettings(){ return this.settings; } 

This works fine and the settings are correctly set when I check the returned data in .map

But when I try to call GetSettings from the component where I need this data, it returns empty. Service defined in bootstrap.

Do I need to change the 'settings' variable? Any help would be greatly appreciated!

Tnx!

+5
source share
3 answers

I would cache in your service using the do statement:

 private settings : settingsModel; constructor(public http: Http){ this.settingsObservable = this.http.get('/settings') .map(response => response.json()) .do(settings => { this.settings = settings; }).share(); } getSettings() { if (this.settings) { return Observable.of(this.settings); } else { return this.settingsObservable; } } 
+2
source

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.

+7
source

why don't you use your service as follows: -

  public settings : settingsModel; constructor(public http: Http){ } GetSettings(){ return this.http.get('/settings') .map(response => { this.settings = response.json() // here setting your data to `this.setting` return this.settings; }) .catch(err => { console.log(err) // handle your error as you want to handle }) } 

and use the .subscribe() method where you want to get the data and show it in the view

+1
source

All Articles