我正在使用TypeScript处理Angular(1.4.9)应用程序。我正在做一个$ http的帖子,并且正在使用一种方法在注册页面上触发成功或失败的警报。我意识到我必须通过我用来触发警报的方法的上下文,所以通常我会做类似的事情:
public showAlert(alertType: string, alertTitle: string, alertMessage: string, alertTimeout: number): void {
this.alertShow = true;
this.alertType = alertType;
this.alertTitle = alertTitle;
this.alertMessage = alertMessage;
this.alertTimeout = alertTimeout;
}
public postIt(): void {
that: any = this; // <-- See, I know what I'm doing.
var url: string = "/";
var user: any = {};
this.$http.post(url, user)
.then((data: any) => {
that.showAlert("success", "Yes!", "You are registered.");
})
.catch((err: any) => {
that.showAlert("warning", "Embarrassing...", "Problem on our end. Try again, later.");
});
}
但是,我喜欢,#34;不是TypeScript聪明到足以知道我在做什么,在这里? Aren的箭头功能为我处理这个问题?&#34;所以,我改变它:
public postIt(): void {
// var that: any = this; <-- Boom! ...Commented out!
var url: string = "/";
var user: any = {};
this.$http.post(url, user)
.then((data: any) => {
// it doesn't like the "this"
this.showAlert("success", "Yes!", "You are registered.");
})
.catch((err: any) => {
// it doesn't like the "this"
this.showAlert("warning", "Embarrassing...", "Problem on our end. Try again, later.");
});
}
我觉得我很聪明。 TypeScript合作。我检查了解释的JavaScript,它正在做我想的那样:
myClass.prototype.postIt = function () {
// var that: any = this;
var _this = this;
var url = "/";
var user = {};
this.$http.post(url, user)
.then(function (data) {
_this.showAlert("success", "Yes!", "You are registered.");
})
.catch(function (err) {
_this.showAlert("warning", "Embarrassing...", "Problem on our end. Try again, later.");
});
...我的应用程序运行正常。但是,编译器会抛出一个错误:&#34; TS2346:提供的参数与调用目标的任何签名都不匹配。&#34;考虑到这种情况,我想阅读它,因为它无法找到方法。当我以原始方式获得它时,它不会进行此投诉。你能解释一下这个错误是什么吗?为什么这个错误不能阻止编译?
答案 0 :(得分:22)
错误信息实际上解释了什么是错误的。方法showAlert
需要4个参数,并且所有参数都是必需的,但postIt
方法showAlert
内部没有alertTimeout
参数。要使此编译器错误消失,您应该在调用alertTimeout
时传递showAlert
值或更新方法的签名并使最后一个参数可选:
public showAlert(alertType: string, alertTitle: string,
alertMessage: string, alertTimeout?: number): void {
...
}