我正在Angular打字稿环境中工作。我通过HTTP获得了一个不错的JSON对象,它很好地映射到ResultViewPlotCfg
结构:
export class ResultViewPlot {
cfg: ResultViewPlotCfg
data: ResultViewPlotData
}
export class ResultViewPlotCfg{
y_parameter: string;
x_parameter?: string;
y_title?: string;
x_title?: string;
y_max?: number;
y_min?: number;
}
export class ResultViewPlotData
{
pom?: number[][];
ref?: number[][];
res?: number[][];
}
我需要将其转换为PlotlyGraph
结构,如下所示:
class PlotlyGraph {
data : [
{x:number[], y:number[], type:string, mode:string, name:string, line?:{color:string, dash:string}},
{x:number[], y:number[], type:string, mode:string, name:string, line?:{color:string, dash:string}},
{x:number[], y:number[], type:string, mode:string, name:string, line?:{color:string, dash:string}}
];
layout : {
yaxis?: {title?:string, range?:number[] },
margin?: {l?:number, r?:number, t?:number, b?:number }
};
}
我的翻译是在PlotlyGraph
结构的构造函数中完成的,如下所示:
constructor( plot : ResultViewPlot)
{
this.data =
[
{x: plot.data.ref[0], y: plot.data.ref[1], type:'scatter', mode:'lines', name:'ref', line:{color:'blue', dash:'solid'} },
{x: plot.data.res[0], y: plot.data.res[1], type:'scatter', mode:'lines', name:'sim', line:{color:'green', dash:'longdash'} },
{x: plot.data.pom[0], y: plot.data.pom[1], type:'scatter', mode:'lines', name:'pom', line:{color:'grey', dash:'dashdot'} }
]
this.layout = {
yaxis: {
title: plot.cfg.y_title,
range: [plot.cfg.y_min, plot.cfg.y_max]
},
margin:{l:50, r:20, t:10, b:40}
};
}
plot.cfg.y_min
可能不存在我现在的窍门是y_max
和y_min
可能不存在。这意味着如果它们存在于PlotlyGraph
中,则仅应在ResultViewPlotCfg
中进行设置。但是我不知道实现该目标的语法是什么。
我尝试过:
if (plot.cfg.y_max && plot.cfg.y_min) {
this.layout.yaxis.range = [plot.cfg.y_min, plot.cfg.y_max];
}
但是我似乎无法输入if
语句。即使我这样做,我怀疑它会删除this.layout.yaxis.title
而不是对其进行扩充。将新数据添加到现有结构的正确语法是什么?