Search code examples
javascriptangularangular8angular2-changedetection

why every time constructor and ngOninit is called in angular when navigate to component?


** 1 .suppose a scenario like i am having navbar and there are tabs in that navbar home and login first when i do ng serve the component of home is called inside it constructor and ngOninit is also invoked . suppose now i navigate to the login component this also invoked its constructor and ngOninit . Now if i again navigate back to the home why there is again constructor and ngOninit called
2. i am trying to make an web app in the home component i fetch the data from the firebase inside the home ngOninit . So when initial application load it get data from the firebase . if i again navigate back to the home component from the login component again home comp call the ngOninit and the it again hit get service method and then it takes to full apllication reload is there any work around . Please give me solution**


Solution

  • The basic thing you have to understand is angular is a SPA (Single Page Application) with life cycle hooks for components that can provides methods that the developer or coder can tap into and use for his/per purpose.

    Since every component is a class, definitely when the component is evoked, the constructor will be evoked. And as per definition of NgOnInit, so will it.

    The workaround we have for your problem is, to implement a shared service.

    Have a service which can store the data that you're fetching from firebase. When you navigate from the intial component, and back, in ngOnInit() hook, try to see whether the shared service already has this data. If there is no data, it means, it is the first loading (or reloading) and the data has to be fetched from firebase. If there is data, it means it has already fetched and kept data and we do not need to get data again.

    Example :

    import { Injectable } from '@angular/core';
    import { BehaviorSubject } from "rxjs/BehaviorSubject";
    
    @Injectable()
    export class SharedService {
    
      dataFromFireBase: string;
    
      constructor() {
      }
    
      updateData(data) {
        this.dataFromFireBase = data;
      }
    }
    

    And in the component :

    import { Component, AfterContentChecked } from "@angular/core";
    import { SharedService } from "../../common/shared.service";
    
    @Component({
      selector: "app-component1",
      templateUrl: "./component1.component.html",
      styleUrls: ["./component1.component.css"]
    })
    export class Component1Component implements AfterContentChecked {
      dataFromFB;
      constructor(private sharedService: SharedService) {}
    
      ngAfterContentChecked() {
        if(!this.sharedService.dataFromFireBase) {
        // you fetch data from firebase into the variable 'dataFromFB'
        this.sharedService.updateData(this.dataFromFB);
        }
      }
    }