如何调用函数eveytime打开一个组件? [英] How to call a function eveytime a component is opened?

查看:121
本文介绍了如何调用函数eveytime打开一个组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个连接到Firebase数据库并下载所有项目的应用程序,然后这些项目显示在这样的表中:

I have an app which connects to a firebase database and download all items then the items are displayed in tables like this:

仅当Im登录后才显示此表,但是一旦我移至另一个组件并返回带有表的组件,就不再加载数据.

This table is only shown if Im logged in but as soon as I move to another component and return to the one with the tables, the data is not loaded anymore.

我认为这是因为我在onInit()函数中具有以下代码:

I think that's because I have the following code in onInit() function:

  ngOnInit() {
    this.taskService.getTasks().subscribe(tasks => {
      this.tasks = tasks;
    });
  } 

基本上只是读取数据并将其添加到数组中. 然后,如果数组长度> 0,则数据将显示在表中:

Which basically just read the data and add it to an array. Then If the array length is > 0 the data is displayed in the tables:

<div *ngIf="tasks?.length > 0;else noTasks">
</div>

我尝试使用

  ngOnChanges() {
    this.taskService.getTasks().subscribe(tasks => {
      this.tasks = tasks;
    });
  }

但是什么都没有改变. 所以..是否有一种方法可以在每次加载组件或我的问题与另一件事有关时调用函数?

But nothing changes. So.. it's there a way to call a function everytime a component is loaded or my problem has to do with another thing?

推荐答案

由于我的评论为您提供了解决方案,因此我将详细说明答案.

Since my comment gave you the solution, I'll elaborate on the answer.

所有继承了Observable的类(Subject,BehaviourSubject,ReplaySubject以及当然是Observable本身)基本上都是您订阅的流,它会记住您的回调,直到您取消订阅为止.

All Classes that inherits Observable (Subject, BehaviourSubject, ReplaySubject and ofcourse Observable itself) is essentially a stream that you subscribe to, which remembers your callback until you unsubscribe.

因此,重要的是最终退订任何已订阅的内容.

It's therefore important to eventually unsubscribe from any subscription made.

除非: 一些可观察对象是从内部关闭的.在示例中,所有HttpClient动词. (获取,发布,放置..)

UNLESS: Some Observables are closed from within. In example all the HttpClient verbs. (get, post, put..)

至少有三种跟踪组件订阅的方法,最简单的一种或两种订阅方式是将它们保存在一个变量中,当您分配该变量时可以取消订阅.

There are at least three ways of keeping track of your components subscriptions, and the easiest one for one or two subscriptions is to save them in a variable which you can unsubscribe when approperiate.

  //Variable to keep track of the subscription
  taskSubscription: Subscription;

  //Creating the subscription
  ngOnInit(){
    this.taskSubscription = this.taskService.getTasks()
        .subscribe(tasks => this.tasks);
  }

  //Calling unsubscribe on the subscription variable when the component is destroyed
  ngOnDestroy(){
    this.taskSubscription.unsubscribe();
  }

这篇关于如何调用函数eveytime打开一个组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆