2

I am looking to create a super generic API Resolver in my application. I want all "GET" requests, possibly extend it to other verbs in the future, to use this resolver. I want to be able to pass the URL and the verb of the request to the resolver and then handle making the function call from there.

This resolver will be used on any Angular route definition with a param called "id" and I want to be able to specify the return type for this resolver.

This is conceptually what I am looking to do, but obviously it does not work due to implementing the interface through Angular.

export class ApiResolve<T> implements Resolve<T> {
  constructor(private _httpClient: HttpClient) { }

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot, requestUrl: string, requestVerb: 'get'): Observable<T> {
    return this._httpClient.request<T>(requestVerb, `${requestUrl}/${route.data['id']}`);
  }
}

{ path: `user/:id`, component: UserComponent, resolve: { user: ApiResolver<User>('api.com/users', 'get') } }
mlangwell
  • 335
  • 1
  • 3
  • 12

1 Answers1

2

It seems the only viable way to transmit information to the resolver is to use the route data object:

export class ApiResolve<T> implements Resolve<T> {
  constructor(private _httpClient: HttpClient) { }

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):  {
    const resolverData = route.data.resolverData;
    return this._httpClient.request<T>(resolverData.method, `${resolverData.url}/${route.data['id']}`);
  }
}

{ 
  path: `user/:id`, 
  component: UserComponent, 
  resolve: { user: ApiResolver<User> },
  data: { resolverData: {url: 'api.com/users', method: 'get'}}
}
255kb - Mockoon
  • 6,657
  • 2
  • 22
  • 29
  • Although I was hoping for something else this definitely does resolve the issue for now. I feel like having to add it to the data property is somewhat inconvenient. Thanks for the idea! – mlangwell Mar 27 '20 at 18:59
  • I also genuinely interested in how to achieve this. But apparently this is the easiest way. – 255kb - Mockoon Mar 27 '20 at 22:04
  • @Guillaume The code "ApiResolver" gives me this error: "Value of type 'typeof ApiResolver' is not callable. Did you mean to include 'new'?" – BigJ Dec 23 '20 at 23:19