How to redirect to an external URL from angular2 route without using component?
angular, angular2-routing, javascript
Solution
You can create a RedirectGuard:
import {Injectable} from '@angular/core';
import {CanActivate, ActivatedRouteSnapshot, Router, RouterStateSnapshot} from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class RedirectGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
window.location.href = route.data['externalUrl'];
return true;
}
}
Import it in app.module:
providers: [RedirectGuard],
And define your route:
{
path: 'youtube',
canActivate: [RedirectGuard],
component: RedirectGuard,
data: {
externalUrl: 'https://www.youtube.com/'
}
}
Problem
I would like to create an external redirect, but to make all routes consistent I think it would be nice to do everything(including external redirects) under Router States configuration. so: ``` const appRoutes: Routes = [ {path: '', component: HomeComponent}, {path: 'first', component: FirstComponent}, {path: 'second', component: SecondComponent}, {path: 'external-link', /*would like to have redirect here*/} ]; ``` UPD: and I don't want to use empty component for this case like @koningdavid suggested. This solution looks really weird for me. It should be something really easy to implement for such case, without virtual components.