How to dynamically use an interface?

时间:2017-12-18 05:06:59

标签: angular

I'm writing up an SDK and I'm using a method callApi to do the repetitive work for building up an http request.

Here it is:

private callApi(method: string, route: string, options?: object, body?: object) {

// build up query parameters
let params = new HttpParams();
if (options) {
  _.forOwn(options, (val, key) => {
    params.append(key, val);
  })
}

// get and delete don't have a body
if (method == 'get' || method === 'delete') {
  return this.http[method](this.apiurl + route, {
    params: params,
    headers: new HttpHeaders().set('Authorization', 'Bearer ' + this.GetToken())
  })
} else {
  return this.http[method](this.apiurl + route, body, {
    params: params,
    headers: new HttpHeaders().set('Authorization', 'Bearer ' + this.GetToken())
  })
}
}

I'd like to call it with another method, for example:

ListCategories: (options?: object) => {
  return this.callApi('get', '/me/categories', options)
},

But I'd also like to somehow have it call that method with an interface specific to the method calling it.

So for example when I call ListCategories I would expect this generic method callApi to somehow be aware of the interface specific to listing categories. How might I accomplish this? I've tried passing the interface, but as I'm reading about interfaces it doesn't look like they exist during run time.

1 个答案:

答案 0 :(得分:0)

Seems like you are looking things like interceptors. If that is the case you can use angular interceptor.

Else look for the below-given soln using http.request method.

get()