router.navigate and router.navigateByUrl not working
Asked Answered
M

0

9

I am saving the requested Url in the localstorage, redirect to an identity-server, this one redirects back to my root url, and then i want to navigate to the previously saved url.

I am saving the url in a guard:

canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> {

    const hasAccessToken$ = Observable.of(this.oAuthService.hasValidAccessToken());

    const setRedirect$ = hasAccessToken$
      .filter(isAllowed => !isAllowed)
      .do(() => localStorage.setItem('login.redirect', state.url)) // save requested url for later redirect
      .do(() => this.oAuthService.initImplicitFlow());

    setRedirect$.subscribe();
    return hasAccessToken$;
  }

And I'm trying to redirect in my app.component.ts:

ngOnInit() {
    this.oAuthService.tryLogin({ onTokenReceived: () => this.redirect() }); // try to parse token from url
  }

private redirect() {
    const url = localStorage.getItem('login.redirect');
    console.log(url);
    this.router.navigateByUrl(url);
  }

My routing look like this:

const routes: Routes = [
    {
        path: 'files',
        loadChildren: './folder-page/folder-page.module#FolderPageModule',
        canActivate: [AuthGuard]
    },
    {
        path: 'recent',
        loadChildren: './recent-page/recent-page.module#RecentPageModule',
        canActivate: [AuthGuard]
    }
];

If i try to access /recent, it will be stored correctly in the localstorage, the console.log output correctly prints '/recent' but no navigation happens. The Page stays in the root url ('/').

I've already tried hard coding the urls ('/recent' and 'recent') and using the other function router.navigate(url) (also tried hard coded).

EDIT Wrapping the navigation with setTimeout (1000) works...but that can't be the right solution

Moxa answered 6/6, 2017 at 9:59 Comment(2)
Can you config a route with dump component, without guard and try to use the navigateByUrl to this route. Not sure why it is not working on your case. angular.io/docs/ts/latest/api/router/index/…Arelus
also not working :-(Moxa

© 2022 - 2024 — McMap. All rights reserved.