简体   繁体   中英

Unsubscribe from Firestore stream - Angular

Recently I implemented Firebase into my Angular project and I have a question about unsubscribing from data stream.

When you use classic HTTP calls, observables from this are finite, but with the firestore, these are infinite, so you have to unsubscribe. But when I do so (after destroying component and log out), I still get an error in console and I can see that requests are still sending (or persisting).

In the network tab I can see this in the request timing:

Caution: request is not finished yet

This error pops up after I log out (Its probably caused because of my rules that I set)

FirebaseError: Missing or insufficient permissions

And also, I still get an error even if I use async pipe in angular.

Here is my current solution:

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();
  }

Thanks for your advices!

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 is what u needed

Use one of the rxjs operators, eg take (1) after taking the value, it unsubscribe by itself

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM