我正在为应该看起来很简单的过程而苦苦挣扎。将序列化的JSON字符串解析为TS对象
在“geolocate.ts”函数“setData”中,模型索引?从“model.flightplan”或“model.config”引用时,Chrome调试器会显示“flightplan”和“config”为“未定义”。即使在调试器中展开时,“模型”对象本身似乎也很好。
任何想法或指针将是非常赞赏;)
geolocate.d.ts
export class FmsFlightPlan {
public status: string[];
...
}
export class Config {
public airportIcon: IconSettings;
...
}
export class InitModel {
public config: Config;
public flightplan: FmsFlightPlan;
}
geolocate.ts
import * as passedData from "./geoLocate.d";
let config: passedData.Config;
let flightPlan: passedData.FmsFlightPlan;
export function setModel(json: string): void {
console.log(json); // '{"Config": { "AirportIcon": {...} ...}, {"Flightplan": {"Status": [], ... } ...}' --- As expected (JSONlint OK)
const model: passedData.InitModel = JSON.parse(json);
console.log(model); // Chrome console: {Config: {…}, Flightplan: {…}}
flightPlan = model.flightplan; // flightPlan and config are assigned "undefined"
config = model.config; // "model" looks OK and Intellisense works.
flightplanDraw();
}
TSC生成的JavaScript
function setModel(o) {
console.log(o);
var e = JSON.parse(o);
console.log(e), flightPlan = e.flightplan, config = e.config, flightplanDraw()
}
.NET的核心观点的Javascript
function gmapsReady() {
initMap();
$.getJSON("/Home/GetConfig",
null,
function(data) {
setModel(data);
});
}
.NET MVC控制器
public JsonResult GetConfig()
{
// Load fplan and config objects
...
...
InitModel initModel = new InitModel
{
Flightplan = fplan,
Config = _config
};
string json = JsonConvert.SerializeObject(initModel);
return new JsonResult(json);
}
尝试'flightPlan = model.Flightplan'并确保名称完全相同,包括大写字母。 JS中的JSON区分大小写( –
@ Helder De Baere:非常感谢您的建议,但是使用model.Flightplan会导致TSC编译错误(如预期的那样) – JcMaltaDev
然后我建议在您的应用程序中重命名'flightplan' InitModel到'飞行计划',也用于配置。如果这样做不起作用,那么解析JSON到你的模型可能有问题 –