How to resolve application level data in angular 4?

Let's say I have a global config that needs to be loaded for all urls.

For example:

/
/users
/users/abc

      

I can manually add the resolver to all urls one by one, but in this case, I need to update the global config from each component that captures the route data, right? Is there a better way to handle this?


Let's say we have several modules:

App Module
/login
/sign-up

User Module
/user/list
/user/:id

Product Module
/product/list
/product/:id

      

@DeborahK we still have to add a resolver for each module root route, I can tell this will definitely work. But is there a way to just apply once in one place?

+4


source to share


3 answers


If you have a parent and child routes, you can set the resolver to the parent and use it in the child. I have an example here: https://github.com/DeborahK/Angular-Routing/tree/master/APM-Final

My parent and child routes look like this. Note that the resolver is for the parent only.

  {
    path: ':id/edit',
    component: ProductEditComponent,
    resolve: { product: ProductResolver },
    canDeactivate: [ProductEditGuard],
    children: [
      {
        path: '',
        redirectTo: 'info',
        pathMatch: 'full'
      },
      {
        path: 'info',
        component: ProductEditInfoComponent
      },
      {
        path: 'tags',
        component: ProductEditTagsComponent
      }
    ]
  }

      



Then you can read the recognizer data from the child like this:

ngOnInit(): void {
        this.route.parent.data.subscribe(data => {
            this.product = data['product'];

            if (this.productForm) {
                this.productForm.reset();
            }
        });
    }

      

I am watching for changes, so subscribe. If you don't need to keep track of changes, you can use a snapshot.

+2


source


I am also trying to find the best approach here for angular 4 and from my tests it seems that

a) You cannot put the solution at the top level, meaning the resolution will not cascade if you have multiple functional modules.



b) Putting a resolver at the root of each function module where you need the data makes the resolver run unnecessarily (for example, every time you move between components from different function modules).

So, I find that resolvers are not very well suited for loading data in applications and it is probably best to look into other methods like APP_INITIALIZER or ways to inject something into bootstrap (for example it looks interesting: angular2 bootstrap with data from ajax calls (s) ). It would be interesting to know what others have found most appropriate. Good luck and please check if you find anything interesting.

0


source


I will answer the same question here, with an example of how to use the tokenAPP_INITIALIZER

0


source







All Articles