简体   繁体   中英

Angular 5 async pipe doesn't work with FirebaseDatabase

I'm trying to experimenting with Angular 5 and Firebase (Using angularfire2 ), and trying to observe the behavior of async pipe.

It was stated that whenever we attach async pipe to an observable it will automatically unsubscribe to the subscription whenever component got destroyed (ie ngOnDestroy() ).

However , when I attach async pipe to FirebaseDatabase , see code below

// This is 'app.component.ts'
import { Component, OnInit, OnDestroy } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
  $mycourses;

  constructor(private firebaseDB: AngularFireDatabase) {
  }

  ngOnInit() {
    this.$mycourses = this.firebaseDB.list('courses').valueChanges();
  }

  ngOnDestroy() {
    console.log('Component Destroyed');
  }
}

while

// This is 'app.component.html'
<h1>My Current Courses:</h1>
<ul>
  <li *ngFor="let course of $mycourses | async">
    <p class="course">{{ course.COURSE }}</p>
    <span class="course-code"> - {{ course.COURSE_CODE }}</span>
    <span class="au"> - {{ course.AU }}</span>
  </li>
</ul>
<button (click)="ngOnDestroy()">Destroy Component</button>

the expected behavior wasn't happening , ie after clicking Destroy Component button, whenever i modify list and object on Firebase Console, my component still reflect the changes on database immediately, while it was supposed to not reflect the changes.

What am I doing wrong here?

Calling ngOnDestroy does not destroy the component.

https://angular.io/api/core/OnDestroy :

Lifecycle hook that is called when a directive, pipe or service is destroyed.

ngOnDestroy callback is typically used for any custom cleanup that needs to occur when the instance is destroyed.

This means that you can do custom unsubscriptions in the ngOnDestroy function that would be called when the component is getting destroyed.

If you want to test component destruction, create a child component, and use templates :

<ng-container *ngIf="existingComponent">
 <child-component></child-component>
<ng-container>
<button (click)="existingComponent = !existingComponent">Create/Destroy</button>

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