How to refresh the screen in Angular?

Asked

Viewed 9,163 times

2

Observe the code below;

import { Location } from '@angular/common';
@Component({
  selector: 'app-node-paginate',
  templateUrl: './node-paginate.component.html',
  styleUrls: ['./node-paginate.component.css']
})
export class NodePaginateComponent implements OnInit {
  constructor(private location: Location) {}

  ngOnInit() {
      this.load();
  }

  load() {
      location.reload()
    }

This code above it performs a refresh on the screen uninterruptedly, but what I really need is for it to do only a refresh.

My goal is when the user access the page, the page can perform a refresh of screen, but it needs to be only a refresh and not several as is happening today.

At the request of Guilherme Costamilam

That’s the problem I’m having too; inserir a descrição da imagem aqui

I’m using the version 6 angular.

I also tried this way to know what came out on the console.;

import { Component, OnInit, HostListener } from '@angular/core';
import { Location } from '@angular/common';

@Component({
  selector: 'app-node-paginate',
  templateUrl: './node-paginate.component.html',
  styleUrls: ['./node-paginate.component.css']
})
export class NodePaginateComponent implements OnInit {
  public innerWidth: any;



  constructor(private location: Location) {}

  ngOnInit() {
      this.innerWidth = window.innerWidth;
      console.log(this.innerWidth);
      this.load();
  }

  load() {
    console.log(sessionStorage);
    //Session storage salva os dados como string
    (sessionStorage.refresh == 'true' || !sessionStorage.refresh) && location.reload();
    sessionStorage.refresh = false;
  }

  @HostListener('window:resize', ['$event'])
  onResize(event) {
    this.innerWidth = window.innerWidth;
  }

}

And I got that result;

inserir a descrição da imagem aqui

But I don’t understand why you’re not recognizing the variable refresh

4 answers

1

I faced a similar problem, to solve I put a variable in my Service, something like:

export class MyService {
  reload = true;
  constructor() { }
}

And in my component I created the function reload that changes the route and then goes back to the current route (I do not know if in your case it would solve, as it is a component only Reload and not the application as a whole):

  reload() {
    if (this.myService.reload) {
      this.router.navigateByUrl('/', { skipLocationChange: true }).then(() => {
        this.router.navigate(['minha-rota']);
        this.myService.reload = false;
      });
    }
  }

With this just put it to rotate on ngOnInit:

  ngOnInit() {
    this.reload();
  }

Obs: My case was a little different, I had to do reload after certain user action, I tried to adapt to your reality, I do not know if it will have any colocateral effect.

1

Maybe you can accomplish with Session Storage even though I would do it a little differently.

ngOnInit() {
  this.load();
}

load() {
  const HAS_RELOAD = 'hasReload';  // Ao invés de passar a string 'hasRealod' diretamente é melhor criar uma constante para evitar erros de digitação
  const hasReload = sessionStorage.getItem(HAS_RELOAD);
  if (!hasReload) {
    sessionStorage.setItem(HAS_RELOAD, 'true');
    location.reload();
  }
}

1

From what I understand your second code is working, since you posted the result of the console. So after making the first refresh he stops there since the sessionStorage.refresh has the value false. Already the first code is really looped but just use the example of the second to fix the first.

Code tested and working taken from your example:

import { Component } from '@angular/core';
import { Location } from '@angular/common';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  constructor() { }

  ngOnInit() {
      console.log('ngOnInit', (new Date()).toTimeString());
      this.load();
  }

  load() {
    console.log('sessionStorage', sessionStorage);
    (sessionStorage.refresh == 'true' || !sessionStorage.refresh) 
        && location.reload();
    sessionStorage.refresh = false;
  }
}

But I don’t understand why you’re not recognizing the refresh variable

There is a typing validation in Typescript and for this reason you are receiving the message "TS: The refresh property does not exist in the Storage type" since this property does not actually exist in localStorage nor in the sessionStorage.

One solution is to use the methods sessionStorage.getItem("refresh") and sessionStorage.setItem("refresh", "true") instead of using the "Object Like (sessionStorage.minhaPropriation) mode". Another alternative is to type as any:

(<any>(localStorage)).refresh
(localStorage as any).refresh

Searching a little more, inside the VS Code press the ctrl and click under the sessionStorageuntil you reach the definition of your interface. There should be the last line of the code below:

interface Storage {
    /* ... conteúdo omitido */
    setItem(key: string, value: string): void;
    [name: string]: any;
}

If not, check your Tslint version or include this last line and the above message will disappear.

Reference of this problem: https://github.com/Microsoft/TypeScript/issues/26083

1

Simply put, store in Session/Location Store whether or not it has already been reloaded and use as a condition to reload:

ngOnInit() {
  this.load();
}

load() {
  //Session storage salva os dados como string
  (sessionStorage.refresh == 'true' || !sessionStorage.refresh) && location.reload();
  sessionStorage.refresh = false;
}

You may also have a variable in the url that defines this, but instead of just reloading, you would have to redirect to another url, for example, dominio.com/foo/true/ will recharge, dominio.com/foo/false/ or dominio.com/foo will not reload, then in your component you check the value of the variable in the url instead of the Session/local Storage

  • the variable refresh was not recognized in my Angular project.

  • I edited the answer with a correction, it could be that, if not, of a console.log(sessionStorage.refresh) at the angle and comment on reload, the expected value appears?

  • there’s no way I can give a console.log(sessionStorage.refresh) because it says that the refresh property does not exist as 'Storage''

  • is giving compilation error? If so, define how : any. I tested it here and it worked normal, which version of you?

  • I updated my post, could take a look please.

  • Constamilam I tried to define the refresh variable as any so public refresh: any; as a global variable, but it did not work.

  • Try to use window.sessionStorage

  • I tried to use it that way window.sessionStorage.refresh == 'true'didn’t take

  • makes a console.log(sessionStorage), appeared the object in the browser console? Also try sessionStorage.get('refresh') and sessionStorage.set('refresh', true), if it doesn’t work does the same with localStorage

  • I just started the console.log and I can find refresh, but I can’t understand why you can’t recognize the variable refresh, please take a look at my post, I just updated.

  • The problem is the typing of the ts that in comfort sometimes, with the get and set didn’t work?

  • does not work the get and set.

  • Do you want me to make my project available through github for you to take a look? It’s a simple project, has no database integration!

Show 8 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.