Search code examples
angularangular-universal

Angular Universal - parent component always refresh


I have noticed interesting behaviour while using angular universal. In short, the project was about a web portal, and I configured it in a way that categories are fetched from the backend via API call through the main component, but I have noticed that ngOnInit of the main component is called each time I change the rout even if the all the routes are child components to the main component. Is there any way I can make my main component call categories only once?


Solution

  • Yes, you can make the main component call the categories API only once, using a service to store the categories data.

    You can create a service that makes an API call and stores the received ranges in a property.

    Then, you can inject the service into both the main component and child components that need access to the category data.

    I wrote a sample typescript code for you.Hope this will help to get an idea for your issue.

        import { Injectable } from '@angular/core';
        import { HttpClient } from '@angular/common/http';
        
        @Injectable({
          providedIn: 'root'
        })
        export class CategoriesService {
          categories: any;
        
          constructor(private http: HttpClient) { }
        
          fetchCategories() {
            if (!this.categories) {
              this.http.get('api/categories').subscribe(categories => {
                this.categories = categories;
              });
            }
          }
        }
        
        
    
        import { Component, OnInit } from '@angular/core';
        import { CategoriesService } from './categories.service';
        
        @Component({
          selector: 'app-main',
        })
        export class MainComponent implements OnInit {
          constructor(private categoriesService: CategoriesService) { }
        
          ngOnInit() {
            this.categoriesService.fetchCategories();
          }
        }
            
    
    
        import { Component, OnInit } from '@angular/core';
        import { CategoriesService } from './categories.service';
        
        @Component({
          selector: 'app-child',
        })
        export class ChildComponent implements OnInit {
          categories: any;
        
          constructor(private categoriesService: CategoriesService) { }
        
          ngOnInit() {
            this.categories = this.categoriesService.categories;
          }
        }