Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 Dependency Injection in UrlMatcher

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.

like image 852
Or'el Avatar asked Jan 16 '19 17:01

Or'el


1 Answers

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,
];
like image 81
Антон Ефанов Avatar answered Oct 31 '22 00:10

Антон Ефанов