调用firebase对象的函数始终返回true

时间:2017-07-11 09:28:21

标签: angular typescript firebase firebase-realtime-database angularfire2

我试图比较2个firebase对象countregs和maxregs。我想像这样返回一个布尔值,但我总是认为不管值是多少。 如果打印出的值显示countregs = 3和maxregs = 5,那么它应该返回false。

谢谢!

getMaxRegs(company: string) {
    var snapshotMaxRegs = this.db.object(`companies/${company}/maxregs`,{ preserveSnapshot: true})

    snapshotMaxRegs.subscribe(snapshot => {
        console.log('maxRegs = '+ snapshot.val())
        return snapshot.val();
    });
}

getCountRegs(company: string){
    var snapshotCountRegs = this.db.object(`companies/${company}/countregs`,{ preserveSnapshot: true})

    snapshotCountRegs.subscribe(snapshot => {
        console.log('currRegs = '+ snapshot.val())
        return snapshot.val();
    });
}

maxRegsReached(company: string){
    if (this.getCountRegs(company) >= this.getMaxRegs(company)
        || this.getCountRegs(company) == this.getMaxRegs(company))
    {
        return true;
    } else {
        return false;
    }
}

2 个答案:

答案 0 :(得分:0)

您的函数getCountRegsgetMaxRegs都返回undefined,它们包含的唯一return语句嵌套在回调函数中,并且它们调用的函数是异步的。你需要开始异步思考:

async getMaxRegs(company: string): Promise<number> {
  const snapshotMaxRegs = this.db.object(`companies/${company}/maxregs`,{
    preserveSnapshot: true});

  return snapshotMaxRegs.map(snapshot => snapshot.val()).toPromise();
}

getCountRegs(company: string): Promise<number> {
  const snapshotCountRegs = this.db.object(`companies/${company}/countregs`,{
    preserveSnapshot: true});

  return snapshotCountRegs.map(snapshot => snapshot.val()).toPromise();  
}

async maxRegsReached(company: string) : Promise<boolean>{
  const count = await this.getCountRegs(company);
  const max = await this.getMaxRegs(company);
  return count >= max; 
}

然后调用this.maxRegsReached()调用函数也必须声明async并且必须await结果。

始终牢记await表示您在等待结果时可以运行所有其他代码。

答案 1 :(得分:0)

由于您的getMaxRegsgetCountRegs在技术上不会返回任何内容,因此您将无法进行有意义的比较。

您应该做的是使用getMaxRegsgetCountRegs.map()方式返回Observable,而不是订阅它。然后,您可以在.forkJoin中加入两个observable(使用maxRegsReached())并比较返回的两个值。

getMaxRegs(company: string) {
    var snapshotMaxRegs = this.db.object(`companies/${company}/maxregs`,{ preserveSnapshot: true})

    return snapshotMaxRegs.map(snapshot => {
        console.log('maxRegs = '+ snapshot.val())
        return snapshot.val();
    });
}

getCountRegs(company: string){
    var snapshotCountRegs = this.db.object(`companies/${company}/countregs`,{ preserveSnapshot: true})

    return snapshotCountRegs.map(snapshot => {
        console.log('currRegs = '+ snapshot.val())
        return snapshot.val();
    });
}

maxRegsReached(company: string){

    return Observable.forkJoin([
        this.getCountRegs(company),
        this.getMaxRegs(company)
    ]).map((joined)=>{
        let countRegs = joined[0];
        let maxRegs = joined[1];

        return countRegs >= maxRegs;
    })
}

现在您需要订阅maxRegsReached才能获得结果:

this.maxRegsReached('company name').subscribe(result => {
        console.log(result) //true or false
})