How to Make a Generic Resolver in Angular (2+)

霸气de小男生 提交于 2021-02-10 17:50:34

问题


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') } }

回答1:


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'}}
}


来源:https://stackoverflow.com/questions/60870662/how-to-make-a-generic-resolver-in-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!