2017-01-03 88 views
1

我有一个操作,我使用angularfire2从我的firebase中获取一些数据,映射它并对数据做一些更新/检查,然后我想再次保存它,但是我有这个奇怪的问题,它告诉我'this.fs.getRiders'是未定义的?但我使用服务来创建流,我不确定这里发生了什么。Angular 2服务调用未定义Angularfire 2流?

继承人一些代码

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

任何人有想法?

+0

@RaiVu将错误重新格式化为简单的降价报价使得读取堆栈跟踪变得更加困难。请不要做这样的编辑。 – cartant

回答

5

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

在这种情况下,我发现'bind'更方便,因为参数的数量并不重要。在所有其他情况下使用箭头功能是恕我直言首选(已添加到我的答案)。感谢您的反馈:) –

+0

不客气。很高兴听到你能使它工作。 –