Getting data from http for every page

Hello I want to download the json data from server and then assign the data to the globally available variable.
I did something like this:

import {Injectable} from '@angular/core';  
import { Http, Headers, RequestOptions } from '@angular/http';

@Injectable()
export class GlobalService {  

    public loginState:boolean = false;
    public player: any = [];

    constructor(public http: Http) {

      this.http.get('http://localhost/ionic/retrieve-data.php')
      .map(res => res.json())
      .subscribe(data =>
      {
        this.player = data;
        console.log(this.player.user);
      });
    }

}

and in other pages i inject it in constructor, but all i can see is empty variable player, loginstate is working.
How can I get the data ti the variable, so I can see this in other pages?

My rule is “only subscribe in pages”, so I would change your service to expose a getPlayer() method that returns an Observable<Player> and then subscribe to that in each interested page. Organizing things this way designs away race conditions such as you have here.

1 Like

Can you explain me more how it should look?

I made it in app.component and then saved it to global.service variable and it works, but I think there is other better solutions.

I don’t think I can say much more than I already have at this point. If you would like to post more of what you have, then perhaps I could.