How can I inject dependencies for a route's UrlMatcher
and perform asynchronous route matching?
I need to make a call to a back end API in order to find out the right route for each URL (by parsing rewrite rules and running queries in WordPress).
That's why I need a singleton service for the UrlMatcher
to fetch the data once and then use it to determine the route (and then inject it to the component with the fetched data).
I created a UrlMatcher factory:
{
component: PostComponent,
matcher: wpApiUrlMatcherFactory('post')
}
But I don't know how to inject the same service to all of the matchers and how to make it work since the service is asynchronous and UrlMatcher
can't return a Promise
or an Observable
.
1.In main.ts
:
export let appInjector: Injector;
platformBrowserDynamic().bootstrapModule(AppModule)
.then(m => appInjector = m.injector)
2. In your router module:
import {appInjector} from '../../main';
const routes: Routes = [
{
matcher: (segments: UrlSegment[]): UrlMatchResult => {
if (appInjector.get(AccessService).hasAccess('test')) {
return {consumed: [segment]};
}
},
component: TestComponent,
];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With