我花了一天时间研究这个主题,但没有找到任何线索。我所找到的只是omission,因为我读过的任何内容都表明你can使用非简单类型(我的意思是string
and number
)用于调用 Angular 4.4 时的通用接口(“shape”)HttpClient.<T>get()
.
下面的示例代码不是无法描述问题,而是我想要做的:
// Injected in my real code ... but these are the libs being used.
import { HttpClientModule } from '@angular/common/http';
import { Observable } from "rxjs";
import 'rxjs/Rx';
interface IMyDataItem {
// In this example, using @Types/Decimal.js
// It appears the "problem" exists for any types beside the simples (number/string etc)
results: decimal.Decimal[];
}
class Service {
doSomethingCool() {
this._http
.get<IMyDataItem>("url://somewhere")
.subscribe(
data => {
// Call a method on the Decimal typed property
data.results[0].pow(3, 3);
}
);
}
}
从语法上来说它可以编译。 TypeScript 正确解决了通用魔法 - 并认识到这一点data.results
是一个类型的数组Decimal
.
然而在运行时(在 Chrome 中,转译为 Javascript 后)调用pow()
失败,指出该方法不存在(事实上,调试它表明它是一个普通的旧 Javascript 对象)。
我对 TypeScript 和 Angular 4 非常陌生——但这对我来说是合乎逻辑的。我只问了通用的get()
调用将请求作为接口进行处理。它必须确定如何构造一个实现该接口的对象。我没有在任何地方构建过实现该接口的实体对象,也没有在任何地方构建过Decimal
.
(更新:这篇文章进一步让我相信我的直觉......https://jameshenry.blog/typescript-classes-vs-interfaces/ https://jameshenry.blog/typescript-classes-vs-interfaces/)
The 官方文档 https://angular.io/guide/http#typechecking-the-response(事实上,我观察到的每个非官方来源)都证明它可以与(用我的话来说)“简单”类型(特别是number
and string
) - 我的直觉说“有道理”,因为JSON
对象可以有简单的字符串和简单的数字。
我错过了显而易见的事情吗?或者直接映射到更复杂的类类型是不可能的吗?
如果不可能——您通常如何处理?我一直在寻找“最佳实践”模式,但结果却不尽如人意。
再说一遍,我的直觉(而且只是my gut说我应该在类中拥有一个私有方法来处理 API 请求 - 并返回一个Observable
(调用者将订阅的)这给出了一个复杂的对象类型(例如一个数组User
类,其中具有与用户相关的方法):
class Service {
// Return a complex object type Observable for consumption elsewhere
doSomethingCool(): Observable<IMyDataItem> {
return this._http
.get<IMyDataItem>("url://somewhere");
}
}
那有意义吗? TIA。