【问题标题】:Angular 2 Service call is undefined from Angularfire 2 stream?Angular 2 服务调用未从 Angularfire 2 流中定义?
【发布时间】:2017-01-03 06:41:26
【问题描述】:

我有一个操作,我使用 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)

有人有想法吗?

【问题讨论】:

  • @RaiVu 将错误重新格式化为简单的降价引用会使读取堆栈跟踪变得更加困难。请不要进行此类修改。

标签: angular rxjs angularfire2


【解决方案1】:

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

【讨论】:

  • 我发现bind 在这种情况下更方便,因为参数的数量无关紧要。在所有其他情况下,恕我直言,首选使用箭头功能(已添加到我的答案中)。感谢您的反馈:)
  • 不客气。很高兴听到你可以让它工作。
猜你喜欢
  • 2017-08-14
  • 1970-01-01
  • 2017-12-14
  • 2017-02-03
  • 1970-01-01
  • 2016-06-20
  • 1970-01-01
  • 2017-10-07
  • 2016-04-12
相关资源
最近更新 更多