Applying the solution to the root component in Angular2

In Angular2, we can use Resolve as follows:

 import { UserResolver } from './resolvers/user.resolver.ts'; export const routes: RouterConfig = [ { path: 'users/:id', component: UserComponent, resolve: { transaction: UserResolver } } ]; 

But how can I best use a recognizer to run, for example, my app.component.ts ? Perhaps when the site loads for the first time, no matter what page the first page is loaded on, I always need to get user data first (for example). So how can I apply this resolver down the route hierarchy?

+6
source share
1 answer

I was wondering about the same thing.

It turns out that if the initial request to the site refers to a path that has one of its components protected by the solution, the solution will be executed before any component in the tree is instantiated. Including AppComponent .

Now the problem is that AppComponent itself is NOT a routable component and therefore cannot access permitted data. Perhaps you could insert ActivatedRoute into the AppComponent and access the data through the current children route, but it seems hacky.

I usually install a solution (or CanActivate guard) at the root of my route hierarchy to retrieve this source data. The data itself is returned by the service and wrapped inside a ReplaySubject . This ensures that 1) the data will be shared by all subscribers; 2) the code receiving the data will be executed only once.

In other words:

  • I use observable to retrieve async data once and share it with all parts of my application that needs it.
  • I rely on a route system to initiate this observable as early as possible in the application life cycle.

(But I do not use a routing system to retrieve data and share it.)

Update to respond to comments:

You must enter a dummy parent route to support security, for example:

 const routes: Routes = [ { path: '', // This is the "root route" component: PageShellComponent, canActivate: [AuthGuard], children: [ { path: 'home', component: PageHomeComponent }, { path: 'inbox', component: PageInboxComponent }, { path: 'settings', component: PageSettingsComponent } ] }, ]; 

The parent route is the β€œroot of my route hierarchy,” and its AuthGuard protection is AuthGuard to ALL child routes in the application. As you can see, the parent route has an empty path, and PageShellComponent contains only <router-outlet></router-outlet> . The sole purpose of this route is to maintain guard (s).

I must add that this is not very idiomatic, and I'm not sure if this is the best way to go.

+2
source

Source: https://habr.com/ru/post/1015224/


All Articles