kfir124
kfir124

Reputation: 1306

Angularjs2 the same service doesn't share data?

I have the following service:

@Injectable()
export class TopplayersService {
  private topPlayers: TopPlayers[];

  constructor() {}

  private getTopFromServer() {

    if (!this.topPlayers) {
      console.log(this.topPlayers);
      // get from server
      this.topPlayers = TOPPLAYERS;
    }
    // return the cached version
    return this.topPlayers;
  }

Now when I have a component that uses this service and I create this component twice (in the html there are 2 tags for it)

I have noticed that getTopFromServer will always log this.topPlayers as undefined and thus will always query the server

Why is that? I'm pretty sure that a service is shard among all the components who uses it

EDIT: this is how I inject the service:

@Component({
  selector: 'top-players',
  template: require('./top-players.html'),
  styles: [require('./top-players.scss')],
  providers: [TopplayersService],
  directives: [],
  pipes: []
})
export class TopPlayersComponent {
  @Input()
  // from where to start to take the top players (1 for example)
  start: number;
  @Input()
  // where to end the top players (5 for example)
  end: number;

  topPlayers: TopPlayers[];

  constructor(public topplayersService: TopplayersService) {}
  onSummonerClick(player) {
      alert('clicked on: ' + player.name);
  }
  ngOnInit() {
    this.topplayersService.getTop(this.start,this.end).then(topplayers => this.topPlayers = topplayers);
  }

}

Upvotes: 1

Views: 108

Answers (1)

Sjoerd
Sjoerd

Reputation: 1305

If you want to share a service over multiple components, you need to provide the service at (shared) parent. In your example the service is injected for each component, meaning that each component has its own instance of the service.

For more information about the hierarchical dependency injector please check the documentation on the Angular2 website: https://angular.io/docs/ts/latest/guide/hierarchical-dependency-injection.html

Upvotes: 2

Related Questions