Lucio Crusca
Lucio Crusca

Reputation: 1517

Async pipe and subscribe on the same Observable

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?

Upvotes: 3

Views: 1257

Answers (2)

Jobelle
Jobelle

Reputation: 2834

CheckThis

this.todosList = this.appService.getTodos().pipe(tap((x:any) => {
      x.map(i => console.log(i.id))
    }))

Upvotes: 0

S Overfow
S Overfow

Reputation: 161

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));

Upvotes: 0

Related Questions