0

I am using 6.1.3 angular HTTP fetching every time I navigate to a component using routing. I am new to angular.

Can anyone please help.

I am fetching data in ngOnninit I think it is the problem

enter image description here

import { Component, OnInit } from '@angular/core';
import * as $ from 'jquery';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {

  constructor(
    private httpDataGetter: HttpClient
  ) { }

  ngOnInit() {
    this.httpDataGetter.get('https://my-json-server.typicode.com/alifrontend499/userdatafake/profile').subscribe(responsive => {
      $(responsive).each((count, obj) => {
        this.userdata.push(obj);
      });
    }, err => {
      console.log(err);
    });
  }

  userdata = []

}

i want the values to be fetched when i navigate to the link in my (case its home component) i used routing it worked and when fetching values it worked too but as i used this.http.get() in ngOninit when i first navigate to homecomponent it fetches values which is good but when i navigate to login and come back to homecomponent it fetches values again. i dont want it .is there any other way?

Community
  • 1
  • 1
Ali Mir
  • 126
  • 10
  • As you are putting the fetch logic in the `onInit`, it should load data every time i guess. its better if you can explain the problem more though. – Shanaka Rusith Aug 23 '18 at 04:31
  • what ever code you are writting inside ngOnIt(), is gonna be called after constructor instantiation for only one time, you can say on the page reload. So there might not be the problem with code what you have shared. can you explain your problem a bit more – Prasanna Aug 23 '18 at 04:35
  • i have edited the question. pls check if you can help – Ali Mir Aug 23 '18 at 07:26

3 Answers3

1

If you don't want to keep refetching data, then you could move the request into a service and implement caching for that service with a ReplaySubject.

Angular 2 cache observable http result data

Jonah
  • 727
  • 5
  • 12
0

Create a service and hold userdata in that as:

Home service

@Injectable()
export class HomeService {
  private userdata;

  constructor(private http: HttpClient) { }

  getData() {
    if(!userdata) { // it will only hit api if data is not there
        this.http.get('https://my-json-server.typicode.com/alifrontend499/userdatafake/profile').subscribe(responsive => {
            this.userdata = [];
            $(responsive).each((count, obj) => {
                this.userdata.push(obj);
            });
        }, err => {
            console.log(err);
        });
    }  
  }

  get UserData() {
    return this.userdata;
  }
}

HomeComponent

export class HomeComponent implements OnInit {

  constructor(
    private service: HomeService;
  ) { }

  ngOnInit() {
    this.service.getData();
  }

  get userdata() {
    return this.service.UserData;
  }
}

Also it's not good practice to use jQuery with Angular.

Anshuman Jaiswal
  • 5,352
  • 1
  • 29
  • 46
0

The Angular Router destroys the component every time the route changes, also on routing to 'Home' the onInit will be called every time. It's a router / angular life cycle. You can define a reuse strategy, if the conditions are met the router will not destroy the component and reuse the component on routing back. (Will not call the constructor and onInit)

Solutions to this problem is to use a global store (Ngrx) or a global Service that is provided on AppModule level.

Fetch the Data with a Singleton pattern, when null / undefined make the http call if not return the Object.

RouteReuseStrategy

G.Vitelli
  • 1,229
  • 9
  • 18