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?