我正在爲應該看起來很簡單的過程而苦苦掙扎。將序列化的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到你的模型可能有問題 –