I have a very simple API call when clicking on minister router link. It displays some data when minister page is open. But I see whenever I came back to that page either from the homepage or any other page the API keeps loading again.
minister.component.ts
import { Component, OnInit } from '@angular/core';
import { ApiReadService } from "../apiReadService.service";
interface mydata{
allMinisters: Object
}
@Component({
selector: 'app-ministers',
templateUrl: './ministers.component.html',
styleUrls: ['./ministers.component.scss']
})
export class MinistersComponent implements OnInit {
allData:Object = [];
constructor(private apiRead: ApiReadService) {
}
ngOnInit(){
this.apiRead.getData().subscribe(data=>{
this.allData = data.allMinisters;
});
}
}
apiReadSerivce.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/Http';
@Injectable({
providedIn: 'root'
})
export class ApiReadService {
constructor(private http: HttpClient) { }
getData(){
return this.http.get('http://localhost:8081/allMinisters')
}
}

ngOnInitis called every time the component is created... which is every time you view the page. As you are callingthis.apiRead.getDatainngOnInityou need a way to cache the data, which Simon_Weaver has shown below... although there are many ways to cache data client side.