Angular 2: pass value for route data

I am trying to write a DataResolver service that will allow an Angular 2 router to preload data before initializing my component.

The solver needs to call different API endpoints to retrieve the data corresponding to the loaded route. Instead of having a resolver for each of my many components, I create one common resolver. Thus, I would like to pass user input in a route definition that points to the correct endpoint. For example, consider these routes:

app.routes.ts

 appRoutes = [ { path: 'project/:id', component: ProjectComponent, resolve: { data: DataResolver } }, { path: 'store/:id', component: StoreComponent, resolve: { data: DataResolver } } ] 

In the first case, the resolver needs to call /path/to/resource1/id . In the second case, /path/to/resource2/id . Ideally, I would pass the endpoint as an argument in the definition of the route, which will then be available in the DataResolver constructor.

Is it possible to do this using a common recognizer class?

Angular 2.0.1 recorded in Typescript 2.0.3

+5
source share
2 answers

I do not know how to make it available in the constructor without using DI. But if you want it to be available in the resolve method, you could just add the data property to the route definition and this will make it available to ActivatedRouteSnapshot

 { path: 'project/:id', component: ProjectComponent, resolve: { data: DataResolver }, data: { path: 'project/:id' } } class DataResolve implements Resolve<string> { resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { return route.data['path']; } } 
+12
source

This answer solved my problem, but I also needed it to be applied if the route has multiple resolvers.

eg.

  { path: 'transactions/showcase/edit/:id', component: ClientsTransactionsFormComponent, resolve: { clients: Resolver, clientTransaction: Resolver, clientTransactionTypes: Resolver }, 

In this case, I solved the problem by passing an array in the data.

 data: ['Clients/GetAll', 'ClientTransactions/GetByID/', 'ClientTransactionTypes/GetAll'] 

and also changed my resolver like this.

 resolve(route: ActivatedRouteSnapshot) { let row = []; let id = ""; Object.keys(route.data).forEach(e => { row.push(route.data[e]); }) let path: string = row[0]; delete row[0]; route.data = row; if (path.lastIndexOf('/') == path.length - 1) { id = route.params['id']; } return this._httpService.httpGet(this.baseUrl + path + id); } 

Hope this helps anyone.

+1
source

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


All Articles