最近,我在 Angular 项目中实现了 Firebase,并且有一个关于取消订阅数据流的问题。
当您使用经典的 HTTP 调用时,从中可观察到的数据是有限的,但使用 firestore 时,这些可观察到的数据是无限的,因此您必须取消订阅。但是当我这样做时(销毁组件并注销后),我仍然在控制台中收到错误,并且我可以看到请求仍在发送(或持续)。
在网络选项卡中,我可以在请求计时中看到这一点:
Caution: request is not finished yet
注销后弹出此错误(可能是由于我设置的规则引起的)
FirebaseError: Missing or insufficient permissions
而且,即使我在 Angular 中使用 async
管道,我仍然会收到错误。
这是我当前的解决方案:
data.service.ts
items: Observable<any[]>;
constructor(db: AngularFirestore) {
this.items = db.collection("data").valueChanges();
}
getItems() {
return this.items;
}
home.component.ts
req: Subscription;
ngOnInit(): void {
this.req = this.dataService.getItems().subscribe(
res => {
console.log(res);
},
err => console.log(err),
() => console.log("completed")
);
}
ngOnDestroy(): void {
console.log("ya");
this.req.unsubscribe();
}
感谢您的建议!
最佳答案
home.component.ts
import { takeWhile } from "rxjs/operators";
@Component({...})
export class HomeComponent implements OnInit, OnDestroy {
isAlive: boolean = true;
...
ngOnInit(): void {
this.dataService.getItems()
.pipe(takeWhile(() => this.isAlive))
.subscribe(res => {
console.log(res);
});
}
ngOnDestroy(): void {
this.isAlive = false;
}
}
takeWhile
是你所需要的
关于javascript - 取消订阅 Firestore 流 - Angular,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59334333/