Can someone help me understand how I can redirect an Angular state to a new URL with the query string parameters same as old ones?
Example
If my Angular application is on http://example.com
, then all the requests to http://example.com/dashboard?id=123&view=test
should be redirected to http://test.com/dashboard?id=123&view=test
.
How should I define my state using the following code?
.state('dashboard', {
url: 'domain.com/dashboard',
controller: 'DashboardCtrl'
})
I know few tricks to transfer the state to controller and then handle it from there. But I'm wondering if there's a way to redirect it through the router only to avoid repetitive code in different controllers?
A. Angular 1
1. main.route.js:
.state('stateName', {
url: 'dashboard',
controller: ['$location', '$window', function ($location, $window) {
var url = 'domainB.com';
url += $location.$$url;
$window.location.href = url;
}]
})
B. Angular2/4
1. app.module.ts: Declare a custom provider like:
@NgModule({
providers: [
{
provide: 'externalUrlResolver',
useValue: (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
window.location.href = `${route.data.externalUrl}${state.url}`;
}
}
]
})
2. app-routing.module.ts: Now using the custom provider we can redirect externally.
const APP_ROUTES: Routes = [
{ path: 'dashboard', component: AnyComponent,
pathMatch: 'prefix',
resolve: { url: 'externalUrlResolver' },
data: { externalUrl: 'domainB.com'}
}
]
Input
This will be redirected to: