当我想在另一个模块中创建全局函数时,我遇到了问题。
utils.ts文件(包含全局函数)
/// <reference path="jquery/index.d.ts" />
/// <reference path="knockout/index.d.ts" />
'use strict';
module com.test.project {
export class utils {
self: any;
constructor() {
this.self = this;
}
public postData(url: string, data: any): any {
var dfd = $.Deferred();
$.ajax({
url: url,
data: JSON.stringify(data),
type: 'post',
contentType: "application/json; charset=utf-8",
dataType: 'json',
cache: false,
success: function(result) {
return dfd.done(result);
},
error: function(result) {
return dfd.reject(result);
}
});
}
}
}login.ts (调用内部的全局函数)
/// <reference path="jquery/index.d.ts" />
/// <reference path="knockout/index.d.ts" />
'use strict';
module com.test.project.login {
export class ScreenModel {
self: any;
userName: KnockoutObservable<string>;
password: KnockoutObservable<string>;
constructor() {
this.self = this;
this.userName = ko.observable("") as KnockoutObservable<string>;
this.password = ko.observable("") as KnockoutObservable<string>;
}
private submit(): void {
var dataObject = {
"userName": this.userName(),
"password": this.password()
}
// ↓ error here
com.test.project.utils.postData("loginService.do", dataObject).done(function(result) {
window.location.href = "index.do";
}).reject(function(result) {
alert("error");
});
}
}
$(document).ready(function() {
ko.applyBindings(new ScreenModel());
});
}模块com.test.project内的全局函数和类中的全局函数通常在com.test.project.function和ScreenModel类模块中调用全局函数。如何在ScreenModel类中调用全局函数?
发布于 2017-07-03 08:15:06
我认为您的想法太多了:我建议您在utils模块中声明一个带有名为postData的函数的对象,并在登录模块中导入该对象。
就像这样:
export const utils = {
postData(url, data) {
$.ajax({})
}
}
// ....
import { utils } from './utils'
utils.postData(url, data)
...或
只导出您的util函数
export function postData(....)
import { postData } from './utils'
postData()发布于 2017-07-03 08:12:00
在你的问题标题中已经有了它:你必须声明它为static,例如public static postData。结果的JavaScript (参见打字稿操场 )有很大的不同。
如果没有静态,则将函数分配给原型,因此需要该类的一个实例来调用该函数。
https://stackoverflow.com/questions/44880574
复制相似问题