【问题标题】:why observable pipe is not working in component?为什么可观察管道在组件中不起作用?
【发布时间】:2020-07-18 07:28:26
【问题描述】:

我有一个使用 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));

我想知道为什么会这样?

【问题讨论】:

标签: javascript angular firebase rxjs observable


【解决方案1】:

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

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,从而保证内存安全而不会泄漏。

【讨论】:

  • 感谢您的回答。基本点在这里“添加管道不会强制对可观察对象进行评估,它会根据管道中定义的额外逻辑创建新的可观察对象实例”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-19
  • 1970-01-01
  • 1970-01-01
  • 2021-03-01
  • 1970-01-01
相关资源
最近更新 更多