繁体   English   中英

Angular 5异步管道不适用于FirebaseDatabase

[英]Angular 5 async pipe doesn't work with FirebaseDatabase

我正在尝试使用Angular 5Firebase (使用angularfire2 ),并尝试观察async管道的行为。

有人说,每当我们将async管道附加到observable时,只要组件被破坏(即ngOnDestroy() ),它将自动unsubscribe订阅。

但是 ,当我将async管道附加到FirebaseDatabase时 ,请参见下面的代码

// 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');
  }
}

// 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>

不会发生预期的行为 ,即单击“ Destroy Component按钮后,每当我在Firebase控制台上修改listobject时,我的组件仍会立即反映数据库中的更改, 本来是不反映更改的。

我在这里做错了什么?

调用ngOnDestroy不会破坏该组件。

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

销毁指令,管道或服务时调用的生命周期挂钩。

ngOnDestroy回调通常用于销毁实例时需要进行的任何自定义清除。

这意味着您可以在ngOnDestroy函数中进行自定义取消订阅,该函数将在销毁组件时被调用。

如果要测试组件销毁,请创建一个子组件,然后使用模板:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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