Skip to content

Commit

Permalink
feat(redirects): Support relative redirects for deeply nested config
Browse files Browse the repository at this point in the history
  • Loading branch information
MikeRyanDev authored and brandonroberts committed May 10, 2016
1 parent 48dc195 commit 3521b56
Show file tree
Hide file tree
Showing 3 changed files with 80 additions and 4 deletions.
55 changes: 55 additions & 0 deletions docs/overview/redirect.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,58 @@ const routes: Routes = [
```

Now when a user navigates to `/blog/:id` they are automatically redirected to `/post/:id`. No more broken links!


### Index Redirects
If you want to redirect only if the path matches a specific route, you can use an index redirect:

```ts
const routes: Routes = [
{
path: '/users',
component: UsersComponent,
index: {
redirectTo: '/'
},
children: [
{
path: ':id',
component: UserByIdComponent
}
]
}
];
```

Now if a user goes to `/users` they will be redirected home but they can still navigate to `/users/:id` safely.


### Relative Redirects
You can also redirect relatively. This is handy for deeply nested links:

```ts
const routes: Routes = [
{
path: '/blog',
component: BlogComponent,
children: [
{
path: ':id',
component: PostComponent,
children: [
{
path: 'change',
redirectTo: 'edit'
},
{
path: 'edit',
component: EditPostComponent
}
]
}
]
}
];
```

If a user navigates to `/blog/123/change` they will be redirected to `/blog/123/edit`.
5 changes: 1 addition & 4 deletions lib/redirect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,9 @@ export class RedirectHook implements Hook<Match> {
const pattern = route.path || '';

parentPattern = pattern.replace(/\/*$/, '/') + parentPattern;

if ( pattern.indexOf('/') === 0 )
break;
}

return '/' + parentPattern;
return parentPattern;
}
}

Expand Down
24 changes: 24 additions & 0 deletions spec/redirect.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,4 +108,28 @@ describe('Redirect Middleware', function() {
expect(observer.next).not.toHaveBeenCalled();
expect(router.replace).toHaveBeenCalledWith('/posts/543', {});
});

it('should relatively redirect if the redirect path is relative', function() {
redirect.apply(routeSet$).subscribe(observer);

routeSet$.next({
routes: [
{ path: '/blog' },
{ path: ':id' },
{
path: 'edit',
redirectTo: 'change'
}
],
routeParams: { id: '543' },
queryParams: {},
locationChange: {
type: 'push',
path: ''
}
});

expect(observer.next).not.toHaveBeenCalled();
expect(router.replace).toHaveBeenCalledWith('/blog/543/change', {});
});
});

0 comments on commit 3521b56

Please sign in to comment.