gpt4 book ai didi

Angular 4-5 HttpClient http get 的强类型

转载 作者:行者123 更新时间:2023-12-03 09:05:04 24 4
gpt4 key购买 nike

我使用帮助程序服务来简化 httpClient 调用。我想对返回的 Observable 进行强类型化。

我的服务,我使用 api 服务并尝试获取发出 > 的强类型可观察对象。

export class ApiUser(){
constructor(private api: Api){}

getUsers(url? : string): Observable<Array<User>>{
return this.api.get<Array<User>>('users'); //here I get errors on types.
}
}

我的 api 帮助器服务,应传递类型:

    import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import {Observable} from "rxjs/Observable";
import {User} from "../../interfaces/interfaces";

/**
* Api is a generic REST Api handler.
*/
@Injectable()
export class ApiService {
constructor(public http: HttpClient) {}

get(endpoint: string, params?: any, reqOpts?: any){

return this.http.get('https://sub.domain.com/api/v1/' +
endpoint,reqOpts);
}
}

所以问题是,这可能不是强类型的正确方法,如果我在 api 帮助程序服务中输入 this.http.get ,它就会起作用,但这违背了强类型的目的帮助服务。

最佳答案

您需要提供type variable给您ApiService.get函数,因为 HttpClient.get假设标准Object当未提供类型时。为此,您可以更新 ApiService.get使用这样的类型变量(例如 T ),如下所示:

get<T>(endpoint: string, params?: any, reqOpts?: any) {
return this.http.get<T>('https://sub.domain.com/api/v1/' +
endpoint,reqOpts);
}

请注意您指定 <T>既作为函数声明 ( get<T> ) 的一部分,又作为传递到 HttpClient.get 的参数.

关于Angular 4-5 HttpClient http get 的强类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47754232/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com