我有一个用 firebase/fireStore 制作的可观察对象。如果我在组件中订阅这个可观察的内容,它就可以工作。但如果我通过管道传递这个可观察的结果,即使我期望它也不起作用。我没有收到任何错误。我的问题;为什么它不起作用?
我的代码;
服务;
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));
我想知道为什么会发生这种情况?
最佳答案
根据docs,添加管道不会强制评估可观察量,它会使用管道中定义的额外逻辑创建新的可观察量实例。 :
A Pipeable Operator is a function that takes an Observable as its input and returns another Observable
要评估新的可观察值,您必须订阅
它,例如使用 .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
将订阅它,接收结果并取消订阅可观察对象,从而保持内存安全而不会泄漏。
关于javascript - 为什么可观察管道在组件中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61057431/