0

I want to make a method on a service that works with AngularFire2 and returns an Observable. I want to update a counter (updating a counter may not be a very scalable example, but that does not really matter here). This is my attempt for the service:

import { Injectable } from '@angular/core';
import { AngularFire } from 'angularfire2';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Injectable()
export class MyService {

  constructor(private af: AngularFire) { }

  updateCounter(): Observable<any>  {
    let counterObserver = this.af.database.object('/variousdata/counter');
    counterObserver.take(1).subscribe(res => {
      let counter = res.$value;
      return this.af.database.object('/variousdata').update({counter: counter+1});
    });
    return counterObserver;
  }

}

And I am using it like this:

let resultObservable = this.myService.updateCounter();
resultObservable.subscribe(
  (obj) => {
    console.log('result:', JSON.stringify(obj));
  }
}

But I am getting only the first result (getting the counter value) printed to the console. How can I get also (or just only) the second one?

I have been somewhat inspired by the example found in Observable type with two http.get calls in Angular 2, but this example did not work so good for my Firebase case, so I have tried to alter it...

Community
  • 1
  • 1
EricC
  • 5,720
  • 13
  • 52
  • 71
  • Well, you di a take(1), then you supposed to get one record! – Fals Nov 08 '16 at 10:15
  • I just want to get the counter-value one time... How can I take the counter-value one time and then increment it and then update it on the server (and at the same time return an Observable when it as finished updating)? – EricC Nov 08 '16 at 10:18
  • I just tested it (changing take to 2), and I still get only one result... – EricC Nov 08 '16 at 10:19

0 Answers0