2

Success 在回调中的成功工厂响应中then调用:

这不起作用,它找不到response

this.storeFactory.getSafes().then(success(response), failure());

如何success正确地将响应传递给函数?

var success = (response: any): void => {
    scope.safes = response.data.safes;
    localStorage.setItem('safeCount', scope.safes.length);
    this.$http.get('/app/dashboard/safes/safes.html', { cache: this.$templateCache }).success((tplContent): void => {
        element.replaceWith(this.$compile(tplContent)(scope));
    }); 
}

长手版效果很好,但我觉得它很乱。

this.storeFactory.getSafes().then((response: any): void => {
    scope.safes = response.data.safes;
    localStorage.setItem('safeCount', scope.safes.length);
    this.$http.get('/app/dashboard/safes/safes.html', { cache: this.$templateCache }).success((tplContent): void => {
        element.replaceWith(this.$compile(tplContent)(scope));
    });
}
4

3 回答 3

2

如何正确传递responsesuccess函数?

没有。您将success函数传递给then方法,然后promise 会将结果值传递给您的success函数。这就是回调的工作原理。

您需要做的就是声明response为函数的参数。不能自己调用​​该函数 - 您只能将其作为回调传递:

this.storeFactory.getSafes().then(success, failure);

此外,您还需要在将函数传递给then. 如果您只声明它们并将undefined值传递给then,它们将被忽略。利用

var success = (response: any): void => {
    scope.safes = response.data.safes;
    localStorage.setItem('safeCount', scope.safes.length);
    this.$http.get('/app/dashboard/safes/safes.html', { cache: this.$templateCache }).success((tplContent): void => {
        element.replaceWith(this.$compile(tplContent)(scope));
    });
};

var failure = (): void => {
    this.$http.get('/app/shared/mocks/tableError.html', { cache: this.$templateCache }).success((tplContent): void => {
        element.replaceWith(this.$compile(tplContent)(scope));
    });
}

this.storeFactory.getSafes().then(success, failure);

但是,箭头函数实际上应该是内联定义的,而不是将它们分配给特定的变量。(您在问题中将此称为“长手版本”,即使它实际上更短)。只需使用它,您就不会遇到这些问题。

一般来说,我建议完全避免在变量赋值中定义函数。如果您需要一个变量,只需使用声明即可(Typescript 语法应该变化不大)。

于 2015-12-09T22:29:41.527 回答
2

我不能说 ES2015 语法或 Typescript,但是你传回success回调的方式看起来很可疑。

代替

this.storeFactory.getSafes().then(success(response), failure());

你应该使用

this.storeFactory.getSafes().then(success, failure);
于 2015-12-09T22:21:59.453 回答
0

AJAX 调用的回调也需要使用箭头函数:

this.$http.get('/app/dashboard/safes/safes.html', { cache: this.$templateCache }).success((tplContent) => {
    element.replaceWith(this.$compile(tplContent)(scope));
}); 
于 2015-12-09T17:17:17.767 回答