javascript - 为什么可观察管道在组件中不起作用?
问题描述
我有一个用 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));
我想知道为什么会这样?
解决方案
根据文档,添加管道不会强制对可观察对象进行评估,它会创建具有在管道中定义的额外逻辑的新可观察实例:
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,从而保持内存安全而不会泄漏。
推荐阅读
- javascript - Laravel AJAX 响应加载错误的路由/窗口
- xslt - 获取每个特定子节点的父节点值
- fortran - cgeev sovle Non Hermitan 矩阵不正确
- django - Django登录 - 不要去注册新用户
- r - 组合学:在不重复元素的情况下随机化,我是否试图做一些不可能的事情?
- ionic-framework - 这个时间/日期时间的类型是什么?
- python - Python 太多的值无法解包
- mongodb - 如何使用 MongoDB shell 获取给定集合的分片键?
- java - Scala/Java - 使用准备好的语句将 BSON 插入 DB2
- python - 递归显示在python中查找最长公共子序列的错误