Search code examples
angularangular5ngoninit

How to call a function eveytime a component is opened?


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

enter image description here 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.

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

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

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>

I tried to solve this by using

  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?


Solution

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

    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.

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