Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass result of one resolve to another with Angular Router

I know how to create multiple resolve classes for a route but I don't know how to pass the result of one resolve to another resolve.

// Example Route
{
  path: 'book/:id',
  component: BookComponent,
  resolve: {
    document: BookResolve,
    title: BookTitleResolve
  }
}

If the BookResolve returns a book object, how can you pass that book object to the BookTitleResolve?

I have a title service that looks for the key title in data. I need to be able to generate the book title from the book object. This needs to be dynamic.

like image 656
Justin Avatar asked Feb 14 '17 23:02

Justin


People also ask

What is resolvers in Angular?

So what is Angular Resolver? Angular Route Resolver is used for pre-fetching some of the data when the user is navigating from one route to another. It can be defined as a smooth approach for enhancing user experience by loading data before the user navigates to a particular component.


Video Answer


1 Answers

Resolves within the same component run concurrently but resolves in parents will complete before children so the easiest way to achieve this is to create a parent route with the purpose of resolving the book.

{
  path: 'book/:id',
  resolve: {
    document: BookResolve
  },
  children: [ {
    path: '',
    component: BookComponent,
    resolve: {
      title: BookTitleResolve
    }
  } ]
}

Note that the parent doesn't render a component and the child contains a blank path so despite some added boilerplate, the route should act the same functionally.

Then inside your BookTitleResolve implementation, you can retrieve from the parent route:

class BookTitleResolve {
    resolve(route: ActivatedRouteSnapshot) {
        // Do something with route.parent.data.document
    }
}
like image 115
DNJohnson Avatar answered Oct 05 '22 07:10

DNJohnson