Reload page after 3 seconds with a promise in Angular

Viewed 1485

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!

2 Answers

This can now be done using the onSameUrlNavigation property of the Router config. In your router config enable onSameUrlNavigation option, setting it to reload . This causes the Router to fire an events cycle when you try to navigate to a route that is active already.

@ngModule({
 imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: 'reload'})],
 exports: [RouterModule],
 })

In your route definitions, set runGuardsAndResolvers to always. This will tell the router to always kick off the guards and resolvers cycles, firing associated events.

export const routes: Routes = [
 {
   path: 'invites',
   component: InviteComponent,
   children: [
     {
       path: '',
       loadChildren: './pages/invites/invites.module#InvitesModule',
     },
   ],
   canActivate: [AuthenticationGuard],
   runGuardsAndResolvers: 'always',
 }
]

Finally, in each component that you would like to enable reloading, you need to handle the events. This can be done by importing the router, binding onto the events, and invoking an initialization method that resets the state of your component and re-fetches data if required.

export class InviteComponent implements OnInit, OnDestroy {
 navigationSubscription;     

 constructor(
   // … your declarations here
   private router: Router,
 ) {
   // subscribe to the router events. Store the subscription so we can
   // unsubscribe later.
   this.navigationSubscription = this.router.events.subscribe((e: any) => {
     // If it is a NavigationEnd event re-initalise the component
     if (e instanceof NavigationEnd) {
       this.initialiseInvites();
     }
   });
 }

 initialiseInvites() {
   // Set default values and re-fetch any data you need.
 }

 ngOnDestroy() {
   if (this.navigationSubscription) {
     this.navigationSubscription.unsubscribe();
   }
 }
}

With all of these steps in place, you should have route reloading enabled. Now for your timeperiod, you can simply use settimeout on route.navigate and this should reload it after desired time.

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){}
Related