necati
necati

Reputation: 187

why observable pipe is not working in component?

I have an observable which is maked with firebase/fireStore. if I subscribe this observable in component it works . but If I pipe this observable it doesn't work even though i expect . and I am not getting any error. my question; why it doesn't work?

my codes;

service;

getLastSeans(uid) {
    return this.afs.doc<any>(`users/${uid}/lastseans/seansLive`).valueChanges();
  }

component;

with pipe it doesn't work

this.roomService.getLastSeans(this.userId).pipe(map(x=>{console.log(x);return x;}));

if I subscribe it work like this;

this.roomService.getLastSeans(this.userId).subscribe(x=>console.log(x));

I want to learn why this happen?

Upvotes: 4

Views: 2451

Answers (1)

Mikhail Tulubaev
Mikhail Tulubaev

Reputation: 4261

Adding a pipe does not force the observable to be evaluated, it creates the new observable instance with extra logic defined in pipes, according to docs:

A Pipeable Operator is a function that takes an Observable as its input and returns another Observable

To evaluate the new observable, you have to subscribe to it, e.g. using the .subscribe call:

this.roomService.getLastSeans(this.userId)
    .pipe(map(x=>{
        console.log(x);
        return x;
    })).subscribe();

Please note, that empty .subscribe is acceptable here, as the logic is defined in the pipes.

Or, altering the template to use the AsyncPipe, e.g:

<app-live-sean *ngFor="let item of liveSeans | async"></app-live-sean>

Assuming that liveSeans is the field of the component, which sets as

this.liveSeans = this.roomService.getLastSeans(this.userId)
    .pipe(map(x=>{
        console.log(x);
        return x;
    }));

In this case AsyncPipe will subscribe to it, receive the results and unsubscribe from the observable, keeping the memory safe without leaks.

Upvotes: 10

Related Questions