Geoff
Geoff

Reputation: 6629

Reload a page once in angular2

I would like to reload a page in angular once when a user visits it but this fails

This is what ive tried

In the homepage component i have

export class HomepageComponent implements OnInit {

  constructor() { }

  ngOnInit() {
    location.reload();
  }

}

The page keeps on refreshing without stopping how can i reload only once on init

Upvotes: 3

Views: 11357

Answers (3)

Uttam Kar
Uttam Kar

Reputation: 323

I got a simple solution as follows

ngOnInit() {
  if (!localStorage.getItem('foo')) { 
    localStorage.setItem('foo', 'no reload') 
    location.reload() 
  } else {
    localStorage.removeItem('foo') 
  }
}

Upvotes: 2

cfphpflex
cfphpflex

Reputation: 603

On Angular 5, I capture the loaded query string param and if exists, stop reloading
because Amcharts is not displaying on first load and only displays on reload

ngOnInit() {
    var urlParams = [];
    window.location.search.replace("?", "").split("&").forEach(function (e, i) {
        var p = e.split("=");
        urlParams[p[0]] = p[1];
    });

    // We have all the params now -> you can access it by name
    console.log(urlParams["loaded"]);

    if(urlParams["loaded"]) {}else{

        let win = (window as any);
        win.location.search = '?loaded=1';
        //win.location.reload('?loaded=1');
    }

}

Upvotes: 1

nekkon
nekkon

Reputation: 107

This will check the query in the url the first time the page gets loaded and will reload right after. This will happen only once (the first time page loads).

ngOnInit(){
      let win = (window as any);
      if(win.location.search !== '?loaded' ) {
          win.location.search = '?loaded';
          win.location.reload();
      }
  }

Upvotes: 1

Related Questions