我在以下代码中遇到了一些问题。
它基本上应该做什么。它应该加载和解析给定的JSON文件。并且在RequestListener中,它应该显示ID
和Product.ts中ToString()
方法返回的字符串Hello
。当tProduct.Id
正确显示时,tProduct.ToString()
方法会失败,并显示下面所述的错误。
提前感谢您的大力协助。
错误信息:
TypeError: tProduct.ToString is not a function.
(In 'tProduct.ToString()', 'tProduct.ToString' is undefined)
文件:Test.ts
var currentProduct = null as pvis.Product;
function runTest(path) {
var request = new XMLHttpRequest();
request.onload = loadRequestListener;
request.open("get", path, true);
request.send();
}
function loadRequestListener () {
var tProduct : pvis.Product = JSON.parse(this.responseText);
if (tProduct.Id) {
currentProduct = tProduct;
alert('loaded with Id: ' + tProduct.Id );
alert('loaded with Content: ' + tProduct.ToString() );
}
else {
alert('product failed to load');
}
}
产品文件Product.ts
module pvis {
export class Product {
Id: string;
ToString():string {
return 'Hello';
}
}
}
HTML部分:
<body onload="runTest('assets/products/json/A379N.json')">
编译后的Javascript代码:
var pvis;
(function (pvis) {
var Product = (function () {
function Product() {
}
Product.prototype.ToString = function () {
return 'Hello';
};
return Product;
})();
pvis.Product = Product;
})(pvis || (pvis = {}));
var currentProduct = null;
function runTest(path) {
var request = new XMLHttpRequest();
request.onload = loadRequestListener;
request.open("get", path, true);
request.send();
}
function loadRequestListener() {
var tProduct = JSON.parse(this.responseText);
if (tProduct.Id) {
currentProduct = tProduct;
alert('loaded with Id: ' + tProduct.Id);
alert('loaded with Content: ' + tProduct.ToString());
}
else {
alert('product failed to load');
}
}
tsconfig.json文件(我不确定它是否相关):
{
"compilerOptions": {
"target": "ES5",
"removeComments": true,
"preserveConstEnums": true,
"out": "js/main.js",
"sourceMap": true
},
"files": [
"src/Test.ts"
]
}
var myParsedAndTypedJson: myInterface = JSON.parse("....");
改为(然后它就可以很好地工作了):var myParsedAndTypedJson: myInterface = new myClass(JSON.parse("...."));
- frank