Javascript 在Angular2中,获取数据后无需用户操作即可更新组件的最佳方法
标题中的问题。 如何在获取数据后更新组件视图而无需用户操作? 现在我必须单击组件来更新表中的数据。真烦人Javascript 在Angular2中,获取数据后无需用户操作即可更新组件的最佳方法,javascript,angular,typescript,Javascript,Angular,Typescript,标题中的问题。 如何在获取数据后更新组件视图而无需用户操作? 现在我必须单击组件来更新表中的数据。真烦人 export class DataStorageService { constructor(private db: AngularFireDatabase, private gameTableService: GameTableService) { } getData() { this.db.database.ref('gameRows').on('value', s
export class DataStorageService {
constructor(private db: AngularFireDatabase, private gameTableService: GameTableService) {
}
getData() {
this.db.database.ref('gameRows').on('value', snapshot => {
this.gameTableService.processData(snapshot.val());
console.log(snapshot.val());
});
}
}
#
{{player.name}
我试图使用subscribe,但组件中的这个更新字段替代了视图中的数据 如果我没弄错你的问题 尝试将此类注入GameTableComponent
constructor(private playerService: PlayerService,
private gameTableService: GameTableService,
private dataStorageService: DataStorageService,
private changedetector: ChangeDetectorRef) {
}
然后,您可以在代码中的任何位置“强制”在ts中检测更改,而不是在用户交互中检测更改
this.changedetector.detectChanges();
如果在subscribe块中定义属性后将其放入,则可以执行上述操作。让我知道它是否有效;) 查看有问题的组件和服务会很有帮助。如果不了解如何获取数据或试图显示数据,很难为您提供帮助。请使用服务并使用该变量来更新HTML。@Mihirtatel好的,当我单击组件时它会起作用。@Jennifer okey,现在应该简单一点。我明白你的想法,但当我在scoreObserver中使用这个方法时,它从未被调用。我正在processData中设置新值,在获取新数据时会调用该值。在这种情况下,可能会出现其他问题,请检查此,是我还是我没有看到getGameRows()方法和getPlayers()方法。将HTML绑定到组件中的gameRows值。
<div class="col border-warning border">
<div class="row">
<div class="col-md-1 text-center">#</div>
<div class="col text-center" *ngFor="let player of playerService.getPlayers()"> {{player.name}}</div>
</div>
<div style="overflow-y: scroll; overflow-x: hidden; max-height: 250px;">
<app-game-row class="text-center" *ngFor="let row of gameTableService.getGameRows()" [gameRow]="row"></app-game-row>
</div>
</div>
constructor(private playerService: PlayerService,
private gameTableService: GameTableService,
private dataStorageService: DataStorageService,
private changedetector: ChangeDetectorRef) {
}
this.changedetector.detectChanges();