简体   繁体   中英

Angular 2 Service call is undefined from Angularfire 2 stream?

I have an operation in which i grab some data from my firebase using angularfire2, map it and do some updates/checks on the data then i want to save it again but i'm having this weird issue where it tells me 'this.fs.getRiders' is undefined? but i'm using a service to create the stream, i'm not really sure what's happening here.

heres some code

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

And the error

 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)

Anyone have ideas?

this is not pointing to where you'd expect

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

With this change this keeps pointing at the current class instance within roundUpdates and saveRound

An alternative way is using arrow functions but they are less convenient in your concrete case

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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