javascript - 在 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(.....=>);
谁能帮忙!!!
提前致谢!!!!
解决方案
您需要将其作为泛型类型参数传递,就像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>
推荐阅读
- c++ - c++ std::bind 函数内
- angular - 如何在 Angular 和 Jasmine 中对退订进行单元测试?
- jquery - 在 touchmove 上禁用 jquery-chosen 以启用页面滚动
- android - 根据字符串长度计数计算ems值
- python - Pyodbc 运行保存的访问查询
- reactjs - React .- JSX 中的 reduce() 不渲染
- c# - 如何防止C#强制excel文件以只读方式打开?
- sql - 循环依赖 - 表插入错误
- grails - Grails GORM:在 beforeUpdate 上更新关联对象的属性未持久化
- java - Weblogic Server 启动期间 JVM 崩溃和巨大的错误日志