首页 > 解决方案 > 在 Angular 中动态传递接口作为参数

问题描述

我很困惑如何将接口作为参数传递并设置为 http get ,post as global

我在全球范围内编写了所有http post、get、put、delete函数

  public get_api(path: string, Interface) {
    return this.http.get<Interface>(API_ENDPOINT + path);
  }

现在我想从另一个 .ts 文件传递​​接口

  this.http_global.get_api('user',Interface).subscribe(.....=>);

谁能帮忙!!!

提前致谢!!!!

标签: javascriptjavaangulartypescript

解决方案


您需要将其作为泛型类型参数传递,就像http.get

public get_api<T>(path: string) {
  return this.http.get<T>(API_ENDPOINT + path);
}

this.http_global.get_api<Interface>('user').subscribe(.....=>);

如果在结果类型中传递的字符串之间存在明确的关系,您可以考虑添加一些重载,以便用户不必指定所有类型的类型:

public get_api(path: 'user'): Observable<User>
public get_api<T>(path: string) : Observable<T>
public get_api<T>(path: string) : Observable<T> {
  return this.http.get<T>(API_ENDPOINT + path);
}

this.http_global.get_api<Interface>('other').subscribe(.....=>);
this.http_global.get_api<('user').subscribe(.....=>); // Observable<User>

推荐阅读