Angularjs2相同的服务不共享数据?

时间:2016-06-04 14:23:54

标签: angular

我有以下服务:

@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;
  }

现在,当我有一个使用此服务的组件时,我创建了两次该组件(在html中有2个标签)

我注意到 getTopFromServer 将始终将 this.topPlayers 记录为未定义,因此将始终查询服务器

为什么?我很确定服务是使用它的所有组件中的分片

编辑:这是我注入服务的方式:

@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);
  }

}

1 个答案:

答案 0 :(得分:2)

如果要在多个组件上共享服务,则需要在(共享)父级提供服务。在您的示例中,为每个组件注入服务,这意味着每个组件都有自己的服务实例。

有关层次依赖注入器的更多信息,请查看Angular2网站上的文档:https://angular.io/docs/ts/latest/guide/hierarchical-dependency-injection.html