Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 2 resolver for every view

So my application is based on angular 2(angular cli) and some CMS. Some fragments of page are downloaded from CMS and displayed on angular 2 page. The main problem is that the header and footer are from CMS. So I wonder how to add global resolver(global is very important, I dont want to add resolver for every route path in application), that will force angular to wait till CMS will return header and footer. I am already successfully using resolver to wait for some data on some routes by implementing route interface

export class InboxResolver implements Resolve<MessageListItem[]>

and I am using it in some custom routes:

const MessagesRoutes: Routes = [
 {
    path: 'inbox',
    component: InboxComponent,
    resolve: { messages: InboxResolver }
 }
];

But how to define one global HeaderAndFooterResolver in one place?

like image 604
user2771738 Avatar asked Dec 05 '16 09:12

user2771738


3 Answers

Not sure what your question is about but you can use a componentless parent route with a resolver and share this with all its child routes

const MessagesRoutes: Routes = [
    { path: '', resolve: { messages: InboxResolver }, children: [
        { path: 'inbox', component: InboxComponent},
        { path: 'xxx', component: XxxComponent},
        { path: 'zzz', component: XxxComponent},
    ]}
];
like image 103
Günter Zöchbauer Avatar answered Sep 26 '22 02:09

Günter Zöchbauer


You basically need one resolver for each component and need to be declare once for each route, unless they are parent > child, you can share the resolver between them like below:

const MessagesRoutes: Routes = [
  { path: '', resolve: { messages: EmailResolver }, children: [
    { path: 'inbox', component: InboxComponent },
    { path: 'outbox', component: OutboxComponent },
    { path: 'sent', component: SentComponent },
    { path: 'received', component: ReceivedComponent }
  ]}
];
like image 36
Alireza Avatar answered Sep 24 '22 02:09

Alireza


Provided you just want to add the resolver to every top level route then something like the below would do it.

   const addGlobalResolver = <T extends Type<Resolve<any>>>(routePaths: Routes, resolver: T, name: string): Routes => {
      return routePaths.map(route => {
        if (route.resolve != null || route.resolve === undefined) {
          route.resolve = {};
        }
        route.resolve[name] = resolver;
        return route;
      });
    };

Just invoke it before you pass the routes to the routing module.

[RouterModule.forRoot(addGlobalResolver(routes, InjuryResolver, 'Injury'))]
like image 29
garty Avatar answered Sep 24 '22 02:09

garty