Wrap HttpClient服务保持打字

时间:2017-09-06 09:34:50

标签: angular typescript

我正在尝试为HttpClient服务创建一个包装器来进行一些个性化设置。 我不想在拦截器中包含一些逻辑,我正在寻找的是在不丢失所有类型的情况下包装该服务。

这是包装器:

template <typename T>
class Bar {
  public:
    T foo;
    void DoSomething() {
      foo.DoSomething();
    }
};

class Foo {
  public:
    Bar<Foo>* bar_ptr;
    void DoSomething() {
      bar_ptr->DoSomething();
    }
};

这是实施:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';

@Injectable()
  export class RestApiService {
  constructor(private http: HttpClient) {}

  get<T>(url: string, options?) {
    return this.http.get<T>(url, options);
  }
}

然后在我的组件中:

import { Injectable } from '@angular/core';
import { EndpointService } from '../endpoint.service';
import { HttpParams } from '@angular/common/http';
import { RestApiService } from '../rest-api.service';

type Product = {
  id: string;
  name: string;
};

@Injectable()
export class ProductService {

  constructor(private restApi: RestApiService, private endPoint: EndpointService) {}

  getThings(sku) {
    const params = new HttpParams()
      .set('ref', sku);

    return this.restApi.get<Product>(this.endPoint.ratings, {params: params});
  }
}

}

这样ngOnInit() { this.productService.getThings(this.sku).subscribe(data => { data }); 就是data,因为打字稿似乎指向了HttpClient的这个签名:

ArrayBuffer

但是应该指出这个签名:

get(url: string, options: {
    headers?: HttpHeaders;
    observe?: 'body';
    params?: HttpParams;
    reportProgress?: boolean;
    responseType: 'arraybuffer';
    withCredentials?: boolean;
}): Observable<ArrayBuffer>;

我如何指出正确的签名? 此外,如果我通过不同的选项,我应该指向正确的签名,所以如果我作为选项get<T>(url: string, options: { headers?: HttpHeaders; observe?: 'body'; params?: HttpParams; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; }): Observable<T>; 传递,我应该指向正确的签名:

responseType: 'text'

我该如何解决这个问题?

0 个答案:

没有答案