简体   繁体   中英

Angular 6 Router doesnt navigate

i have a component(Unlock) which router.navigate doesnt work somehow. I couldnt figure out why router doesnt redirect the page. It only happens in this component. Any ideas ?

submit() {

    if (!this.unlockForm.valid) { return; }
    this.isLoading = true;
    this.userDataService.unlockCpo(this.model).subscribe(data => {
      this.oauthService.refreshToken().then(done => {
        this.translateService.get('UnlockAccount.UnlockSuccess').subscribe((res: string) => {
          this.toastr.success(res);
          this.isLoading = false;
         this.router.navigate(['/dashboard']); // there is not working but debuger goes on the line and no errors thrown..
        });
      }

And there my app.routing.ts

{
        path: 'unlock',
        component: UnlockComponent
    },
    {
        path: 'logout',
        component: LogoutComponent
    },
    {
        path: 'dashboard',
        canActivate: [CloudConnectivityGuard, AccessGuard],
        component: DashboardComponent
    },

Here the canActive method

 canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot) {

    // const hasIdToken = this.oauthService.hasValidIdToken();
    const hasIdToken = true;
    const hasAccessToken = this.oauthService.hasValidAccessToken();

    if (!hasIdToken || !hasAccessToken) {
      this.router.navigate(['/login']);
      return false;
    }
    if (!this.userService.isCpo()) {
      this.router.navigate(['/unlock']);
    }

    return true;
  }
}

You have to create an object of the router as well in your guard.

Also if you return true it will navigate to the page.

constructor(protected router: Router) { }

canActivate() {
    const hasIdToken = true;
    const hasAccessToken = this.oauthService.hasValidAccessToken();

    if (!hasIdToken || !hasAccessToken) {
        this.router.navigate(['/login']);
        return false;
    }

    if (!this.userService.isCpo()) {
        this.router.navigate(['/unlock']);
        return false;
    }

    return true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM