在 Angular 中动态传递接口作为参数

Vya*_*ddy 2 javascript java typescript 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);
  }
Run Code Online (Sandbox Code Playgroud)

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

  this.http_global.get_api('user',Interface).subscribe(.....=>);
Run Code Online (Sandbox Code Playgroud)

谁能帮忙!!!

提前致谢!!!!

Tit*_*mir 5

您需要将它作为泛型类型参数传递,就像这样http.get做:

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

this.http_global.get_api<Interface>('user').subscribe(.....=>);
Run Code Online (Sandbox Code Playgroud)

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

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>
Run Code Online (Sandbox Code Playgroud)