Pipe and Tap VS subscribe with ngxs

自闭症网瘾萝莉.ら 提交于 2021-02-18 10:16:06

问题


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.


回答1:


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



回答2:


Got it! I have to append subscribe(). So it is:

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



回答3:


tap (or do in the old version of RxJS) -> Transparently perform actions or side-effects, such as logging (as definition already says).

But, in your case, you forgot to "subscribe()" to your Observable and that's why you don't see your "User Data" in the Console.

On the other hand, in the second case, you already subscribe to an Observable.



来源:https://stackoverflow.com/questions/50415966/pipe-and-tap-vs-subscribe-with-ngxs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!