2

I'm using async pipe in my template to get a list of users that match a certain condition (getNonRedirectingList). Users are stored in a Firestore instance.

In my component template I have the following (simplified) code:

    <div *ngIf="users$ | async as users" class="uwrapper">
        <div *ngFor="let u of users">{{u.name}}</div>
    </div>

and this works like a charm: it produces 3 <div> blocks, that match the 3 users I'm expecting.

However in the Typescript code I also need to subscribe to the same Observable that @angular/fire returns

ngOnInit(): void {
  this.users$ = this.userSvc.getNonRedirectingList().pipe(share());
  firstValueFrom(this.users$).then(users => {
    for (let i = 0; i < users.length; i++) {
      console.log(i);
    }
  });
}

I'd expect

0
1
2

as output in the console, but I get nothing instead. Even setting a breakpoint at the console.log(i) line, it never gets hit.

I've already tried with and without .pipe(share()), I've also tried calling getNonRedirectingList twice in the hope of getting two different Observable and I've also tried using subscribe() and unsubscribe() instead of firstValueFrom(), but the result was just the same: the async pipe worked, my code did not.

EDIT after S Overflow's answer:

Tried this too, with same results

this.users$.pipe(tap(users => {
  for (let i = 0; i < users.length; i++) {
    console.log(i);
  }
}));

Any clues?

Lucio Crusca
  • 1,277
  • 3
  • 15
  • 41

2 Answers2

0

With async pipe you already subscribe to Observable, so no need of anything else, just append operator, like tap to log the values:

this.users$ = this.userSvc.getNonRedirectingList().pipe(tap(console.log));

S Overfow
  • 141
  • 5
  • Thanks, tried, but It still does nothing: the execution flow does not reach `console.log`. Going to edit my question to include this too. – Lucio Crusca Sep 07 '21 at 15:25
  • Updated to set pipe on same instance of your Observable. `pipe` creates a new instance – S Overfow Sep 07 '21 at 15:32
0

CheckThis

this.todosList = this.appService.getTodos().pipe(tap((x:any) => {
      x.map(i => console.log(i.id))
    }))
Jobelle
  • 2,717
  • 1
  • 15
  • 26