我正在使用现有的 TypeScript
方法,并且正在努力从 promise 中获取 errorCallback
值。 Angular 的类型定义文件中的接口(interface)如下所示:
interface IPromise<T> {
then<TResult>(successCallback: (promiseValue: T) => IHttpPromise<TResult>, errorCallback?: (reason: any) => any, notifyCallback?: (state: any) => any): IPromise<TResult>;
then<TResult>(successCallback: (promiseValue: T) => IPromise<TResult>, errorCallback?: (reason: any) => any, notifyCallback?: (state: any) => any): IPromise<TResult>;
then<TResult>(successCallback: (promiseValue: T) => TResult, errorCallback?: (reason: any) => TResult, notifyCallback?: (state: any) => any): IPromise<TResult>;
我正在使用的 TypeScript
方法调用服务并且 promise 使用返回(这有效):
public loadSavedLogin(): ng.IPromise<MyApp.Models.User> {
return this._myAppService.getUser(this.savedUserId).then((result: MyApp.Models.User) => {
if (result) {
this.userId = result.UserID;
this.userName = result.UserName;
}
return result;
});
}
问题是我不知道如何获取 errorCallback
值。如果我在 .then((result: MyApp.Models.User)
之后放置一个逗号,我会看到 Intellisense 向我显示 errorCallback
参数,但我就是无法获得任何语法的工作原理。在原始 JS
中,我在末尾有一个逗号,另一个函数接受错误值,但我不确定这个接口(interface)如何返回错误。
如果服务调用使用 IPromise
返回错误值,我该如何修改函数以获取错误值?
最佳答案
这是一个可以帮助您解决问题的简化示例。
class Test {
public _test: ng.IPromise<string>;
// This method has a return type of ng.IPromise<string>
// You must return a value of this type.
public example(): ng.IPromise<string> {
return this._test.then(
// Success
// Must return a string to be compatible with
// the ng.IPromise<string> return type
(val) => {
alert('Success');
return val;
},
// Error
// Should also return a string to be
// compatible with the return type
(reason) => {
alert('Error: ' + reason);
return '';
});
}
}
因为 example
方法返回类型是 ng.IPromise<string>
, then
中的成功函数和错误函数方法必须返回 string
为了使类型全部匹配。
在你的例子中,他们应该返回一个 MyApp.Models.User
的实例.
我怀疑你的error
函数你没有返回值 - 但这是成功函数和错误函数之间最好的通用类型 void
.
进一步的例子......在使用函数时只使用一个数组来显示最常见的类型:
var example = [
(input: string) => { return 'String'; },
(input: string) => { console.log(input); }
];
此示例中使用的最常用类型是 (input: string) => void
.看起来很奇怪 - 但它实际上是有道理的。如果调用此数组中的函数,不要期望获得返回值。
因此,只需确保您的成功函数和错误函数具有相同的返回类型,并且所有类型都会匹配您。
public loadSavedLogin(): ng.IPromise<MyApp.Models.User> {
return this._myAppService.getUser(this.savedUserId).then(
(result: MyApp.Models.User) => {
if (result) {
this.userId = result.UserID;
this.userName = result.UserName;
}
return result;
},
(reason: string) => {
return <MyApp.Models.User> null;
}
);
}
关于javascript - 从 IPromise 获取 errorCallback 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26500548/