2016-06-07 16:07:38 -07:00
|
|
|
import {Location, LocationStrategy, PathLocationStrategy} from '@angular/common';
|
|
|
|
import {APP_INITIALIZER, ApplicationRef, ComponentResolver, Injector} from '@angular/core';
|
2016-06-08 11:13:41 -07:00
|
|
|
|
|
|
|
import {RouterConfig} from './config';
|
2016-06-07 16:07:38 -07:00
|
|
|
import {Router} from './router';
|
|
|
|
import {RouterOutletMap} from './router_outlet_map';
|
|
|
|
import {ActivatedRoute} from './router_state';
|
|
|
|
import {DefaultUrlSerializer, UrlSerializer} from './url_serializer';
|
2016-06-08 11:13:41 -07:00
|
|
|
|
2016-05-27 13:51:14 -07:00
|
|
|
|
|
|
|
/**
|
2016-06-07 16:07:38 -07:00
|
|
|
* A list of providers. To use the router, you must add this to your application.
|
2016-05-27 13:51:14 -07:00
|
|
|
*
|
|
|
|
* ### Example
|
|
|
|
*
|
|
|
|
* ```
|
|
|
|
* @Component({directives: [ROUTER_DIRECTIVES]})
|
|
|
|
* class AppCmp {
|
|
|
|
* // ...
|
|
|
|
* }
|
2016-06-08 11:13:41 -07:00
|
|
|
*
|
2016-06-07 16:07:38 -07:00
|
|
|
* const routes = [
|
2016-05-27 13:51:14 -07:00
|
|
|
* {path: '/home', component: Home}
|
|
|
|
* ];
|
|
|
|
*
|
2016-06-07 16:07:38 -07:00
|
|
|
* bootstrap(AppCmp, [provideRouter(routes)]);
|
2016-05-27 13:51:14 -07:00
|
|
|
* ```
|
|
|
|
*/
|
2016-06-08 11:13:41 -07:00
|
|
|
export function provideRouter(config: RouterConfig): any[] {
|
2016-05-27 13:51:14 -07:00
|
|
|
return [
|
2016-06-07 16:07:38 -07:00
|
|
|
Location,
|
|
|
|
{provide: LocationStrategy, useClass: PathLocationStrategy},
|
|
|
|
{provide: UrlSerializer, useClass: DefaultUrlSerializer},
|
|
|
|
|
|
|
|
{
|
|
|
|
provide: Router,
|
|
|
|
useFactory: (ref, resolver, urlSerializer, outletMap, location, injector) => {
|
|
|
|
if (ref.componentTypes.length == 0) {
|
|
|
|
throw new Error('Bootstrap at least one component before injecting Router.');
|
|
|
|
}
|
|
|
|
const componentType = ref.componentTypes[0];
|
|
|
|
const r = new Router(
|
|
|
|
componentType, resolver, urlSerializer, outletMap, location, injector, config);
|
|
|
|
ref.registerDisposeListener(() => r.dispose());
|
|
|
|
return r;
|
|
|
|
},
|
|
|
|
deps:
|
|
|
|
[ApplicationRef, ComponentResolver, UrlSerializer, RouterOutletMap, Location, Injector]
|
|
|
|
},
|
|
|
|
|
|
|
|
RouterOutletMap,
|
|
|
|
{provide: ActivatedRoute, useFactory: (router) => router.routerState.root, deps: [Router]},
|
|
|
|
|
|
|
|
// Trigger initial navigation
|
|
|
|
{
|
|
|
|
provide: APP_INITIALIZER,
|
|
|
|
multi: true,
|
|
|
|
useFactory: (injector) => {
|
|
|
|
// https://github.com/angular/angular/issues/9101
|
|
|
|
// Delay the router instantiation to avoid circular dependency (ApplicationRef ->
|
|
|
|
// APP_INITIALIZER -> Router)
|
|
|
|
setTimeout(_ => injector.get(Router).initialNavigation(), 0);
|
|
|
|
return _ => null;
|
|
|
|
},
|
|
|
|
deps: [Injector]
|
|
|
|
},
|
2016-05-27 13:51:14 -07:00
|
|
|
];
|
|
|
|
}
|