Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve application-level data in angular 4?

Tags:

angular

Let's say I have a global config that should be loaded for all the URLs.

For example:

/
/users
/users/abc

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


Let's say we have multi modules:

App Module
/login
/sign-up

User Module
/user/list
/user/:id

Product Module
/product/list
/product/:id

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

like image 421
PeiSong Avatar asked Oct 17 '22 09:10

PeiSong


1 Answers

If you have parent and child routes you can set a resolver on 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. Notice the resolver is only on the parent.

  {
    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 resolver 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'm watching for changes so have the subscribe. If you don't need to watch for changes you can use the snapshot.

like image 91
DeborahK Avatar answered Nov 15 '22 10:11

DeborahK