繁体   English   中英

Angularfire 2流中未定义Angular 2服务调用?

[英]Angular 2 Service call is undefined from Angularfire 2 stream?

我有一个操作,其中我使用angularfire2从firebase中获取了一些数据,将其映射并对数据进行了一些更新/检查,然后我想再次保存它,但是我遇到了一个奇怪的问题,它告诉我“ this.fs” .getRiders'是未定义的? 但是我正在使用服务来创建流,因此我不确定在此发生什么。

这是一些代码

 @Injectable()
      export class RoundService {

    public currentRound:FirebaseListObservable<any>;

constructor(private af: AngularFire, private as:AuthService, private fs:FirebaseService) { }

pullCurrentRound(serieUid:string){  

  return this.af.database.object(`series/${serieUid}/currentRound`)
    .flatMap((res)=>{
      return this.af.database.object(`rounds/${res.$value}`)
        .map((res)=>res)
        .do(this.roundUpdates)
        .do(this.saveRound)
    })
}

saveRound(round){

    this.fs.getRiders.update(round.uid,round)
      .then(snap=>{
        console.log(snap)
      })
}

和错误

 Uncaught TypeError: Cannot read property 'getRiders' of undefined
at SafeSubscriber.RoundService.saveRound [as _next] (round.service.ts:57)
at SafeSubscriber.__tryOrSetError (Subscriber.js:232)
at SafeSubscriber.next (Subscriber.js:174)
at Subscriber._next (Subscriber.js:125)
at Subscriber.next (Subscriber.js:89)
at DoSubscriber._next (do.js:82)
at DoSubscriber.Subscriber.next (Subscriber.js:89)
at DoSubscriber._next (do.js:87)
at DoSubscriber.Subscriber.next (Subscriber.js:89)
at MapSubscriber._next (map.js:83)

有人有想法吗?

this并不指向您期望的位置

pullCurrentRound(serieUid:string){  

  return this.af.database.object(`series/${serieUid}/currentRound`)
    .flatMap((res)=>{
      return this.af.database.object(`rounds/${res.$value}`)
        .map((res)=>res)
        .do(this.roundUpdates.bind(this)) // <<< changed
        .do(this.saveRound.bind(this) // <<< changed
    })
}

随着这一变化this保持在中当前类的实例指向roundUpdatessaveRound

一种替代方法是使用箭头功能,但在您的具体情况下它们不太方便

pullCurrentRound(serieUid:string){  

  return this.af.database.object(`series/${serieUid}/currentRound`)
    .flatMap((res)=>{
      return this.af.database.object(`rounds/${res.$value}`)
        .map((res)=>res)
        .do(x => roundUpdates(x)) // <<< changed
        .do(round => this.saveRound(round) // <<< changed
    })
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM