0

I'm trying to perform operations with data coming from Firestore. I'm subscribing to an observable using valuechanges() and trying to extract an array of objects so I can create a form based on it.

It's my second time using rxjs and I've tried everything I know but couldn't make it happen. I can console.log my desired array inside the subscription but can't return it so I can use it outside.

this is the ts

export class ExerciseTestsComponent implements OnInit {
  exercises: Observable<any>
  exerciseForm: FormGroup;
  isAnswered: boolean; 
  isCorrect: boolean; 
  helloThere: []


  constructor(
    private fb: FormBuilder,
    private db: AngularFirestore) {}

  ngOnInit(): void {
    let exerciseTest; 
    this.db
    .collection('availableExercises')
    // .doc("xvXCAxUrj4842ItZCyrv")
    // .collection("questions")
    .valueChanges()
    .subscribe(
      res => {
        console.log(res);   
      }
      )
    console.log("below is exerciseTest ")
    console.log(exerciseTest)
    this.createGroup()
  }

  createGroup() {
    console.log("below is my firestore data")
    console.log(this.exercises)
    this.exerciseForm = this.fb.group({});
    this.exercises[0]
    .doc("xvXCAxUrj4842ItZCyrv")
    .collection("questions")
    .forEach(control =>
      this.exerciseForm.addControl(control.prefix, this.fb.control(""))
    );
  }
1
  • You can not return from a concurrent operation! You either have a callback or set a global variable that you set from inside the subscribe. Read more about async nature here stackoverflow.com/questions/14220321/… Commented Mar 5, 2020 at 0:55

1 Answer 1

1

It is a bit confusing as to the problem. I think you're confusing asynchronous nature.

In you're ngonInit() you are calling createGroup as part of the regular method, not as part of the result handler.

  ngOnInit(): void {
    let exerciseTest; 
    this.db
    .collection('availableExercises')
    .valueChanges()
    .subscribe(
      res => {
        console.log(res);   
        // saving the response to a component local variable
        this.exercises = res;
        // I am calling this.createGroup() inside the result handler; not outside of it. 
       // I'm also passing in the response.
       this.createGroup()
      }
      )
  }

Now, you your create group function should have access to this.exercises.

In your original implementation, this.createGroup() was most likely called before the result handler was run; and as such this.exercises would have been undefined. But, it is hard to tell since no where in your original code is this.exercises defined or given a value.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.