Skip to content

Instantly share code, notes, and snippets.

@johan--
Forked from roelofjan-elsinga/dynamic.routes.ts
Created December 9, 2019 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johan--/9814b04dbaf47bdea8e2790400c1fe73 to your computer and use it in GitHub Desktop.
Save johan--/9814b04dbaf47bdea8e2790400c1fe73 to your computer and use it in GitHub Desktop.
Dynamic routes for Angular
import {NgModule} from '@angular/core';
import {HomeComponent} from './home/home.component';
import {AboutUsComponent} from './about-us/about-us.component';
import {ContactComponent} from './contact/contact.component';
export class DependencyInjectionClass {
constructor(private _service: FictionalService) {}
resolve(route, state) {
//Get some fictional data with the id that's in the URL
return this._service.getFictionalData(route.paramMap.get('id'));
}
}
export const DynamicPagesRoutes = {
states: [
{
name: 'home',
url: '/',
component: HomeComponent,
resolve: {
// This will go to the provider of this module,
// where it will be raplaced with a callback function
anyData: 'homePageResolve'
},
parent: 'public'
},
{
name: 'aboutus',
url: '/about-us',
component: AboutUsComponent,
resolve: {
// You may recognize this syntax from the AngularJS UI Router
anyData: ['Dependency', Dependency => {
return {any: 'data'};
}]
},
parent: 'public'
},
{
name: 'contact',
url: '/contact/:id',
component: ContactComponent,
resolve: {
// the router will automatically call
// the resolve method of the provided class
anyDataWithDependencyInjection: DependencyInjectionClass
},
parent: 'public'
},
{
name: 'anotherState',
url: '/another-state/:id',
component: AnotherStateComponent,
resolve: [
// This object is similar to the first option, but inline
{
provide: 'anyDataWithDependencyInjection',
useFactory: (http) => http.get('/'),
deps: [ Http ]
}
],
parent: 'public'
},
{
name: 'yetAnotherState',
url: '/yet-another-state/:id',
component: YetAnotherStateComponent,
resolve: [
// Yet another way to write the resolver inline,
// but pay special attention to the second resolver.
{
token: 'anyDataWithDependencyInjection',
deps: ['UserService', Transition],
resolveFn: (userSvc, transition) => userSvc.fetchUser(transition.params().userId) },
},
{
provide: 'user',
(allusers, trans) => _.find(allusers, trans.params().userId,
deps: [
// You can inject a previous resolver
// in another resolver to use the data
'anyDataWithDependencyInjection',
Transition
]
}
],
parent: 'public'
}
]
}
@NgModule({
imports: [
CommonModule,
SharedModule,
UIRouterUpgradeModule.forChild(DynamicPagesRoutes)
],
declarations: [
HomeComponent,
AboutUsComponent,
ContactComponent
],
providers: [
{provide: 'homePageResolve', useValue: (route, state) => {
return {any: 'data'};
}}
]
})
export class DynamicPagesModule {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment