簡體   English   中英

取消訂閱 Firestore 流 - Angular

[英]Unsubscribe from Firestore stream - Angular

最近我在我的 Angular 項目中實現了 Firebase,我有一個關於取消訂閱數據流的問題。

當您使用經典的 HTTP 調用時,由此產生的 observable 是有限的,但是對於 firestore,它們是無限的,因此您必須取消訂閱。 但是當我這樣做時(在銷毀組件並注銷之后),我仍然在控制台中收到一個錯誤,我可以看到請求仍在發送(或持續)。

在網絡選項卡中,我可以在請求時間中看到這一點:

注意:請求尚未完成

注銷后彈出此錯誤(可能是由於我設置的規則引起的)

FirebaseError:權限缺失或不足

而且,即使我在 angular 中使用async管道,我仍然會收到錯誤消息。

這是我目前的解決方案:

數據服務.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是你需要的

使用 rxjs 運算符之一,例如在取值后取 (1),它會自行取消訂閱

this.dataService.getItems().pipe(take(1)).subscribe(
      res => {
        console.log(res);
      },
      err => console.log(err),
      () => console.log("completed")
    );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM