Search code examples
javascriptangularpromisetimeoutreload

Reload page after 3 seconds with a promise in Angular


I'm trying to implement a solution for the login page. When user passes the wrong login/password I want the page to reload after 3 seconds. I was trying to do it with 2 solutions but can't make it work. The code would launch after click on a button when there is no match for credentials (else condition):

FIRST IDEA:

  ...else{
    this.comUser = 'WRONG LOGIN OR PASSWORD'
    this.alert = ""
    setTimeout(function() { 
      window.location = "I would like it to use the routing to a component instead of URL here"; }
      ,3000);

SECOND IDEA WITH A PROMISE:

const reloadDelay = () => {
  reload = this.router.navigate(['/login']);
  return new Promise((resolve, reject) => {
    setTimeout(() => {
    console.log("działa");
    resolve(reload)
    }, 4000);
  });
};

Thanks for any hints!


Solution

  • If you're using angular 9 you can try this

    setTimeout(() => {this.domDocument.location.reload()}, 3000); 
    

    You need to import:

    import { Inject } from '@angular/core';
    import { DOCUMENT } from '@angular/common';
    

    In order to use the above-mentioned method and have the constructor of component.ts configured as below.

    constructor(@Inject(DOCUMENT) private domDocument: Document){}