Lug*_*ino 5 typescript angular
我正在尝试为HttpClient服务创建一个包装器来进行一些个性化设置.我不想在拦截器中包含一些逻辑,我正在寻找的是在不丢失所有类型的情况下包装该服务.
这是包装器:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
这是实施:
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});
}
}
Run Code Online (Sandbox Code Playgroud)
然后在我的组件中:
ngOnInit() {
this.productService.getThings(this.sku).subscribe(data => {
data
});
Run Code Online (Sandbox Code Playgroud)
}
这种方式data是ArrayBuffer因为打字稿似乎指向HttpClient的这个签名:
get(url: string, options: {
headers?: HttpHeaders;
observe?: 'body';
params?: HttpParams;
reportProgress?: boolean;
responseType: 'arraybuffer';
withCredentials?: boolean;
}): Observable<ArrayBuffer>;
Run Code Online (Sandbox Code Playgroud)
但是应该指出这个签名:
get<T>(url: string, options: {
headers?: HttpHeaders;
observe?: 'body';
params?: HttpParams;
reportProgress?: boolean;
responseType?: 'json';
withCredentials?: boolean;
}): Observable<T>;
Run Code Online (Sandbox Code Playgroud)
我怎样才能指出正确的签名?此外,如果我通过不同的选项,我应指向正确的签名,所以如果我作为选项传递,responseType: 'text'我应该指向正确的签名:
get(url: string, options: {
headers?: HttpHeaders;
observe?: 'body';
params?: HttpParams;
reportProgress?: boolean;
responseType: 'text';
withCredentials?: boolean;
}): Observable<string>;
Run Code Online (Sandbox Code Playgroud)
我怎么解决这个问题?
| 归档时间: |
|
| 查看次数: |
627 次 |
| 最近记录: |