2

I have an Angular app in which users can access using a direct link, containing a token, such as the following:

localhost:3000/token/<alphanumeric string>

The related component does a check for the token validity and if success then loads the page content.

After the users access the app, I would like to change the URL in the address bar, to something like:

localhost:3000/homepage

Here is part of my routing file:

{
  path: 'token/:token-id',
  component: HomepageComponent,
  resolve: {data: TokenResolver}
}

Here is the resolver:

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<UserInfo> {
    const tokenId = route.paramMap.get('token-id');
    const apiURL = `${this.apiRoot}/${tokenId}`;
    return this.http.get<UserInfo>(apiURL)
}

I tried to change the routing in the following way:

{
  path: 'token/:token-id',
  resolve: {data: TokenResolver},
  redirectTo: 'homepage'
},
{
  path: 'homepage',
  component: HomepageComponent
}

I even tried to remove redirectTo and use resolve: {redirectTo: 'homepage', data: TokenResolver}. Both ways don't work. The first one because it seems to execute redirectTo before resolve. The second one because I cannot declare a path without a component, or redirectTo and so on.

So I tried the following way:

routing file:

{
  path: 'token/:token-id',
  component: HomepageComponent,
  resolve: {data: TokenResolver}
},
{
  path: 'homepage',
  component: HomepageComponent
}

resolver file:

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<UserInfo> {
  const tokenId = route.paramMap.get('token-id');
  const apiURL = `${this.apiRoot}/${tokenId}`;
  return this.http.get<UserInfo>(apiURL)
    .pipe(map((data) => {
      this.router.navigate(['homepage'], {state: { data: data }});
      return data;
    }));
}

This works, but as you can see I had to declare HomepageComponent twice in the routing file. In addition I had to return data in the resolve function, even if I'm not using that return anymore.

Do you know a better way to reach what I need?

smartmouse
  • 13,912
  • 34
  • 100
  • 166
  • 1
    The first `HomepageComponent` in your second example does not actually be declared. You just need any dummy component, so that the prod build does not complain. AFAIK your second example is the recommended way to go, and it's what we used in our project. – skolldev Jul 09 '19 at 12:22
  • Can I use an empty component as a dummy component? What about the `return data`? Shouldn't it be unnecessary? – smartmouse Jul 09 '19 at 12:27
  • Yes, you can use an empty component. It is unnecessary, yes. – skolldev Jul 09 '19 at 12:36
  • Yes, it is unnecessary but how to remove it since I'm implementing `Resolve`? – smartmouse Jul 09 '19 at 12:37

0 Answers0