0

I am currently trying to convert an Observable into an Array so that I can iterate over the Array in HTML using ngFor.

This is my Typescript code currently. When I console log the testArray Array it is saying it is undefined.

item$: Observable<any[]>;
testArray: Array<any[]>;

  constructor(
    private afs: AngularFirestore,
    private route: ActivatedRoute,
  ) {
      this.item$ = afs.collection('testsTaken', ref => ref.where('testCreator', '==', this.id).where('testTitle', '==', this.testTitle)).valueChanges();
      this.item$.subscribe(x => this.testArray = x);
      console.log(this.testArray); // yields undefined
 
  }

I tried the advice given for this post and I still cant get it to work

ChristianK
  • 35
  • 1
  • 4

2 Answers2

3

The console.log() is printing undefined because your subscribe emits after the console.log printing so the array is still undefined. You can check it and make the changes like that:

 this.item$.subscribe(x => {
   this.testArray = x;
   console.log(this.testArray);
 });

if you want to run on *ngFor with the array you have 2 options :

Options 1:

this.item$.subscribe(x => this.testArray = x);

you can use it in your template like (example) :

<div class="test" *ngFor="let item of testArray"> {{item}} </div>

Option 2:

Async pipe (you can read more about it here: https://angular.io/api/common/AsyncPipe) in a nutshell that's the same like subscribe in your component type script but in the template (there is a lot of benefits of using it).

example code:

<div class="test" *ngFor="let item of item$ | async">{{item}} </div>;
Medinios
  • 296
  • 2
  • 5
0

An Observable works asynchronous. Javascript does not wait for its result outside the subscription and your console.log() has been fired long before the code inside the Observable is being processed. Look at this:

this.item$.subscribe(x => {
       this.testArray = x;
       console.log(this.testArray);
});