angularuser-interface

First time and during refresh only API call should call and give response


API call should get called in home page during first time page load and during refresh, If navigate from other page to home page, API response should not get update. give some idea how to handle this

I have writing the code like below, and it is not working as expected

Thanks

Example in home.component.ts

ngOnInit() {
this.Service.IpnValue().then(ipn => this.userIpn = ipn);
this.getLoggedOnTime(this.Ipn);    
}



getLoggedOnTime(Ipn: string): void {
    this.ervice.getUserLoggedOn(Ipn).subscribe(
      (response) => {
        this.lastLoggedOnTime=response.code;
        console.log('User logged on:', this.lastLoggedOnTime);
      },
      (error) => {
        console.error('Error logging on user:', error);
      }
    );
  }

Solution

  • First create a property on the service that stores this lastLoggedOnTime (property that should be called only on load).

    Then on first load/refresh only, this property will be undefined use this to trigger the API call like below:

    ngOnInit() {
      if(this.Service.lastLoggedOnTime === undefined) {
        this.Service.IpnValue().then(ipn => this.userIpn = ipn);
        this.getLoggedOnTime(this.Ipn);    
      }
    }
    
    getLoggedOnTime(Ipn: string): void {
      this.Service.getUserLoggedOn(Ipn).subscribe(
        (response) => {
          this.lastLoggedOnTime=response.code;
          console.log('User logged on:', this.lastLoggedOnTime);
        },
        (error) => {
          console.error('Error logging on user:', error);
        }
      );
    }