angular - Scala class isn't deserialised correctly by Angular HttpClient
问题描述
I have the following trait
and classes
in Scala
:
sealed trait Algorithm {
val name: String
val formula: String
val parameters: Seq[AlgorithmParameter[Any]]
def enhanceAlgorithm[T](algorithm: T): Unit
}
case class LinearRegressionAlgorithm(override val name: String, override val formula: String) extends Algorithm {}
case class GeneralizedLinearRegressionAlgorithm(override val name: String, override val formula: String) extends Algorithm {}
sealed abstract class AlgorithmParameter[+T](val name: String, val value: T, val selectOptions: Seq[T]) extends EnumEntry
object AlgorithmParameter extends Enum[AlgorithmParameter[AnyVal]] with CirceEnum[AlgorithmParameter[AnyVal]] {
case object MaxIter extends AlgorithmParameter[Int]("maxIter", 100, Seq())
}
I created in TypeScript
the corresponding classes which look like this:
export abstract class Algorithm {
readonly name: string;
readonly formula: string;
readonly parameters: AlgorithmParameter<any>[];
protected constructor(name: string, formula: string, parameters: AlgorithmParameter<any>[]) {
this.name = name;
this.formula = formula;
this.parameters = parameters;
}
}
export class LinearRegressionAlgorithm extends Algorithm {}
export class GeneralizedLinearRegressionAlgorithm extends Algorithm {}
export class AlgorithmParameter<T> {
readonly name: string;
readonly value: T;
readonly selectOptions: T[];
constructor(name: string, value: T, selectOptions: T[]) {
this.name = name;
this.value = value;
this.selectOptions = selectOptions;
}
}
What I'm doing is making a REST request to the backend (Scala part) which returns a sequence of the type Seq[Algorithm]
and I expect that the response will be correctly translated into the Typescript classes, but it doesn't
The REST method looks as follows:
recommend<T extends Algorithm>(body: RecommenderRequest): Observable<T[]> {
return this.http.post<T[]>(environment.baseUrl + this.recommenderPath + this.algoRecommendationsPath, JSON.stringify(body))
.catch((error: any) => Observable.throw(error.json().error || 'Server error'))
}
The response is translated into an array looking as follows:
It seems that the TS algorithm-objects
have been created, but they are encapsulated inside another object and I can't access in an easy way
In order to get the name
of the first algorithm, the call looks as follows:
response[0].LinearRegressionAlgorithm.name
, but I would like to have the Http-response array created in such a way that it would be possible to simply write response[0].name
解决方案
Angular 不会创建这些类型的对象。只是被告知这就是打字。您的 Scala 程序正在返回正在显示的数据。您将需要对每个结果进行映射操作以获取正确的对象。
下面是一个例子:
recommend<T extends Algorithm>(body: RecommenderRequest): Observable<T[]> {
return this.http.post<T[]>(environment.baseUrl + this.recommenderPath + this.algoRecommendationsPath, JSON.stringify(body)).pipe(
map(algorithms => algorithms.map(algorithm => this.toAlgorithm(algorithm)),
catchError(error => Observable.throw(error.json().error || 'Server error'))
);
}
private toAlgorithm(algorithm: { [type: string]: Partial<Algorithm> }): Algorithm {
const type = Object.keys(algorithm)[0];
const name = algorithm[type].name;
const formula = algorithm[type].formula;
const parameters = (algorithm[type].parameters || [])
.map(parameter => this.toParameter(parameter));
switch (type) {
case 'LinearRegressionAlgorithm':
return new LinearRegressionAlgorithm(name, formula, parameters);
case 'GeneralizedLinearRegressionAlgorithm':
return new GeneralizedLinearRegressionAlgorithm(name, formula, parameters);
default:
throw new Error('Unsupported algorithm');
}
}
private toParameter(paramerter: Partial<AlgorithmParameter<any>>): AlgorithmParameter<any> {
return new AlgorithmParameter<any>(parameter.name, parameter.value, parameter.selectedOptions);
}
如果您不需要这些算法的实际实例,而只需要算法中的值,则可以将Algorithm
类更改为接口,这要简单得多:
recommend<T extends Algorithm>(body: RecommenderRequest): Observable<T[]> {
return this.http.post<T[]>(environment.baseUrl + this.recommenderPath + this.algoRecommendationsPath, JSON.stringify(body)).pipe(
map(algorithms => algorithms.map(algorithm => Object.values(algorithm)[0]),
catchError(error => Observable.throw(error.json().error || 'Server error'))
);
}
以这种方式做事你会丢失任何关于算法类型的信息,所以你会想在你的算法接口上为类型添加另一个属性,并在上面的映射过程中设置它。只是取决于你的需要。
推荐阅读
- c# - 在 asp.net core 3 中创建漂亮的 url
- python - ModuleNotFoundError:没有名为“模型”的模块
- google-apps-script - Google 表格不接受来自 appendRow 或 setValues 的数据
- php - OpenSSL 加密函数在 PHP 7.4.5 上不起作用
- javascript - JS/NodeJS JSON 缓冲区到字符串
- x86-64 - 从子指令 x86_64 中得到否定结果
- javascript - 你如何遍历一个对象数组来创建一个新对象?
- google-analytics - 电子商务跟踪谷歌分析
- c++ - OpenCV 的元素乘法给出了意想不到的价值
- r - 使用具有相同列名的变量列表在 data.frame 中追加行 - R 语言