0

I am unable to route to same page and I am not sure what is missing here. If I remove the setTimeout function it is working fine, but not working with setTimeout.

Is there any way I could delay the routing?

{
    path: 'sample-page',
    component: SamplePageComponent,
    canActivate: [SampleGuard]
  }

Here is my SamplePage which will just consume the message from route parameters. The html file just displays the message.

SamplePage

import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-sample',
  templateUrl: './sample-page.component.html',
  styleUrls: ['./sample-page.component.scss']
})
export class SamplePageComponent implements OnInit, OnDestroy {  
  message: string;

  routeParamsSubscription: Subscription;
  constructor(private activatedRoute: ActivatedRoute, private router: Router) {
    console.log(' in constructor');
  }

  ngOnInit(): void {
    console.log('in in ng init');
    this.routeParamsSubscription = this.activatedRoute.params.subscribe(params => {
      this.message = params.message;
    });
  }

  ngOnDestroy(): void {
    this.routeParamsSubscription.unsubscribe();
  }
}

SampleGuard This just navigates to the same page 6 times and then returns false.

import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class SampleGuard implements CanActivate {
  static count = 0;
  private readonly MAX_RETRY_COUNT = 6; // total 6 seconds
  private readonly WAIT_TIME = 1000; // 1 sec

  constructor(
    private router: Router
  ) {}

  canActivate(): boolean {
      if (
        SampleGuard.count <= this.MAX_RETRY_COUNT
      ) {
        ++SampleGuard.count;

        setTimeout(() => {
          this.router.navigate(['/sample-page', { message : 'message' + SampleGuard.count }]);
        }, this.WAIT_TIME);
        return true;
      } else {
        return false;
      }
    }
  }

Thanks in advance.

4

0 回答 0