Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pipe and Tap VS subscribe with ngxs

I am playing around with pipe and subscribe. If I am using pipe with tap, nothing will log in console. If I am using subscribe, it's working. So what I am doing wrong?

import { Observable } from 'rxjs';
import { tap, take } from 'rxjs/operators';

this.store.select(state => state.auth.authUser).pipe(
  take(1),
  tap((data) => {
    //Not Working - no console output
    console.log('[Tap] User Data', data);

  })
);

this.store.select(state => state.auth.authUser).subscribe((data) => {
  // Working - user data output in console
  console.log('[Subscribe] User Data', data);
})

I am using RxJs 6, TypeScript and ngxs as store in Angular 6.

like image 386
Paul Avatar asked May 18 '18 16:05

Paul


1 Answers

My answer is in two parts... What you asked, and what you need 😉. The values of an Observable only flow through the pipe operators when there is an active subscription. That is why you are seeing this behaviour. So you should do something like this:

this.store.select(state => state.auth.authUser).pipe(
  take(1),
  tap((data) => {
    console.log('[Tap] User Data', data)
  })
).subscribe();

But what it seems that you are looking for is a state snapshot. You can do this as follows:

let data = this.store.selectSnapshot(state => state.auth.authUser);
console.log('[selectSnapshot] User Data', data);
like image 185
Mark Whitfeld Avatar answered Sep 23 '22 22:09

Mark Whitfeld