【问题标题】:Angular 5 async pipe doesn't work with FirebaseDatabaseAngular 5 异步管道不适用于 FirebaseDatabase
【发布时间】:2018-04-30 16:36:28
【问题描述】:

我正在尝试使用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时,我的组件仍然会立即反映数据库上的更改, 虽然它不应该反映这些变化。

我在这里做错了什么?

【问题讨论】:

  • 当你的组件被销毁并且不在视图中时,你怎么看组件?

标签: javascript angular firebase firebase-realtime-database angularfire2


【解决方案1】:

调用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>

【讨论】:

    猜你喜欢
    • 2020-09-26
    • 1970-01-01
    • 2019-12-27
    • 2020-07-27
    • 2020-08-24
    • 1970-01-01
    • 2020-03-26
    • 2018-07-18
    • 2021-05-22
    相关资源
    最近更新 更多