Search code examples
javascriptangularangularfire2

How to get first value and then another subscribe method


I have developed a simple angular 7 web app. firebase database connectivity, I am trying to store the first list in an array using the subscribe method and then console.log that array. but before that data get the array will print undefined after some time it will get data. How can code wait for the response is done and then print that array.

import { Injectable } from '@angular/core';
import { AngularFireList, AngularFireDatabase } from 'angularfire2/database';

@Injectable({
  providedIn: 'root'
})
export class DressesService {

  constructor(public firebase: AngularFireDatabase) { }

  getJoinDresses(){
  	return this.firebase.list('makavana-tailor/dresses').snapshotChanges()
  }

}

import { Component, OnInit } from '@angular/core';
import { DressesService } from '../../services/dresses/dresses.service';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-con-dress',
  templateUrl: './con-dress.component.html',
  styleUrls: ['./con-dress.component.css']
})
export class ConDressComponent implements OnInit {

  constructor(private dresses: DressesService) { }
  dressArray = [];

  ngOnInit() {
    this.getAllDresses();
    console.log(this.dressArray)
  }

  getAllDresses(){
    this.dresses.getJoinDresses().subscribe(actions => {
      this.dressArray = actions.map(action => {
        return {
          $key: action.key,
          ...action.payload.val()
        }
      })
    })
  }
}


Solution

  • Your question title is not clear. But if I understand your problem correctly, you are facing an issue in working with asynchronous calls. Either you have to print console.log(this.dressArray) inside the subscribe or return the observable data from getAllDresses and subscribe to it within onInit()

    code :

    ngOnInit() {
        this.getAllDresses().subscribe(data => {
             this.dressArray = data;
             console.log(this.dressArray)
        });
     }
    
    getAllDresses(){
        return this.dresses.getJoinDresses().pipe(map(actions => {
          return actions.map(action => {
            return {
              $key: action.key,
              ...action.payload.val()
            }
          })
        }))
      }