我尝试从firebase获取数据及其成功,但需要几秒钟, 代码继续,因此变量的值为null。 它为什么会发生?它的线程?我该怎么办?
gameslist.component.ts
import {Component} from 'angular2/core';
import {Game} from './Game'
import {NgStyle} from "angular2/common";
import {DataService} from "./data.service";
declare var firebase: any;
@Component({
selector:'gameslist',
templateUrl: 'app/ts/gameslist.component.html',
styleUrls: ['app/ts/gameslist.component.css'],
inputs: ['games'],
directives: [NgStyle],
providers:[DataService]
})
export class gamesListComponent{
public games;
public currentGame=[];
public votes1: number;
constructor(private dataService:DataService){ this.votes1=0;this.currentGame=[];}
fbPostVote(id_game:number,ChooseVote:number){
this.votes1=this.dataService.getGameById(id_game); //Here return null
this.votes1++;
var updates = {};
updates['/games/'+id_game+'/rec_1_votes'] = this.votes1;
updates['/games/'+id_game+'/rec_1_color'] = 'pink';
this.games[id_game].rec_1_color = 'pink';
return firebase.database().ref().update(updates);
}
data.service.ts
import {Injectable} from 'angular2/core';
import {Http, Response} from 'angular2/http';
import 'rxjs/Rx';
@Injectable()
export class DataService{
constructor(private http:Http){ }
getGameById(id_game:number){
firebase.database().ref('/games/'+id_game+'/rec_1_votes').on('value',function(snap) {
return snap.val();
});
}
}
感谢。
答案 0 :(得分:0)
getGameById()
不会返回任何内容。将其更改为
getGameById(id_game:number){
return firebase.database().ref('/games/'+id_game+'/rec_1_votes').on('value',function(snap) {
return snap.val();
});
}