[英]Pass Interface Dynamically as Parameter In Angular
我很困惑如何將接口作為參數傳遞並設置為http get,post作為全局
我全局編寫了所有http發布,獲取,放置,刪除功能
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.