首页 > 解决方案 > 为什么可观察管道在组件中不起作用?

问题描述

我有一个用 firebase/fireStore 制作的 observable。如果我在组件中订阅这个 observable,它就可以工作。但是如果我通过管道传输这个 observable,即使我期望它也不起作用。而且我没有收到任何错误。我的问题; 为什么它不起作用?

我的代码;

服务;

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

零件;

用管道它不起作用

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

如果我订阅它就像这样工作;

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

我想知道为什么会这样?

标签: javascriptangularfirebaserxjsobservable

解决方案


根据文档,添加管道不会强制对可观察对象进行评估,它会创建具有在管道中定义的额外逻辑的新可观察实例:

Pipeable Operator 是一个将 Observable 作为输入并返回另一个 Observable 的函数

要评估新的 observable,你必须这样subscribe做,例如使用.subscribe调用:

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

请注意,.subscribe这里可以接受空,因为逻辑是在管道中定义的。

或者,更改模板以使用AsyncPipe,例如:

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

假设这liveSeans是组件的字段,它设置为

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

在这种情况下AsyncPipe,将订阅它,接收结果并取消订阅 observable,从而保持内存安全而不会泄漏。


推荐阅读