skip to Main Content

I am calling data from Firebase RTDB and that data is in an Observable. The issue I am having here is that, in my .TS file i would like to access the content of the Observable, that thought seems to not be possible.

I need to get in there so I could use certain value to write out some logic for the component, at the moment only place I could access the data is in the HTML using async.

Evrything is in a switchmap because I am change the route using button clicks, so I could pull data from different paths in the DB.

Component .TS

import { Component, OnChanges, OnInit, SimpleChanges, Inject } from '@angular/core';

import { AngularFireDatabase } from '@angular/fire/compat/database';
import { BehaviorSubject, Observable, switchMap } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']

  
})
export class AppComponent  {

// implements OnChanges, OnInit
  time$: Observable<any[]>;
  lineup$: Observable<any[]>;

  x$ = new BehaviorSubject<string>('race_no_1');
  
  constructor(private db: AngularFireDatabase) {
    // Get Lineups
    this.lineup$ = this.x$.pipe(switchMap((x) => {
      return this.db.list('race/'+x).valueChanges();
  }))

    // Get Race Events
      this.time$ = this.x$.pipe(switchMap((x$) => {
          return this.db.list(x$).valueChanges();
      }))
  }
  
  race_no(b: string) {
      this.x$.next(b);
  }
}

I am expecting to get a regular TS array out of this so I could handle component logic using the values in the array . Like adding a json return to array.

How can I get this done quick and simple ?

2

Answers


  1. Chosen as BEST ANSWER

    Just use subscribe as stated in the manual. Link to accessing Observable streams

    lineups$.subscribe(
      value => this.someArray.push(value);
    );
    

    Now you got a new array that is flat.


  2. We have rxjs/operators to handle this specific scenario.

    • map -> Access the data in the observable and you can transform the response by returning the transformed value

    • tap -> Access the data in the observable without modifying the inner contents, but perform side-actions based on the value of the observable!

    So it looks like tap is what you need!

    Your question has not gone into detail on what you want to fix, so here is a high level of how it will look!

      constructor(private db: AngularFireDatabase) {
        // Get Lineups
        this.lineup$ = this.x$.pipe(switchMap((x) => {
          return this.db.list('race/'+x).valueChanges().pipe(
              tap((obsData: any) => {
                  // do something with the obs data!!!!
              })
          );
      }))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search