我使用Typescript创建了一个服务:
class ConfigService implements IConfigService {
public admin = {};
public adminBackup = {};
public user = {};
public loaded = false;
constructor(
private $http: ng.IHttpService,
private $q: ng.IQService
) {
}
static $inject = [
'$http',
'$q'
];
put = ():ng.IHttpPromise<> => {
var defer = this.$q.defer();
if (angular.equals(this.admin, this.adminBackup)) {
return defer.resolve();
} else {
this.$http({
data: {
adminJSON: JSON.stringify(this.admin),
userJSON: JSON.stringify(this.user)
},
url: '/api/Config/Put',
method: "PUT"
})
.success(function (data) {
this.adminBackup = angular.copy(this.admin);
this.userBackup = angular.copy(this.user)
return defer.resolve();
});
}
return defer.promise;
};
}
我也创建了这个界面:
interface IConfigService {
put(): ng.IHttpPromise<>;
}
然而,代码给我一个错误说:
Error 3 Cannot convert 'void' to 'ng.IHttpPromise<any>'.
Error 4 Cannot convert 'ng.IPromise<{}>' to 'ng.IHttpPromise<any>':
Type 'ng.IPromise<{}>' is missing property 'success' from type 'ng.IHttpPromise<any>'.
答案 0 :(得分:19)
使用
ng.IPromise<void>
如果您没有声明返回类型并且不使用该界面,也可以让它为您隐式输入。
这里也应该没有退货声明:
return defer.resolve();
只是:
defer.resolve();
答案 1 :(得分:2)
当我遇到这个问题时,我发现我无法使用ng.IPromise<void>
作为ng.IHttpPromise<>
的声明要求我返回一个对象。
例如:
public saveTechnicianNote = (jobNumber: string, technicianNote: Model.TechnicianNote): ng.IPromise<void> => {
var data = {
jobNumber: jobNumber,
subject: technicianNote.subject,
details: technicianNote.details
};
return this.$http.post(this.urlFactory.saveTechnicianNote, data);
}
引发了Type IHttpPromise<{}> is not assignable to IPromise<void>
。
为了解决这个问题,我让它返回ng.IPromise<any>
。不是100%理想,但这是我能想到的最好的解决方案,不需要我延伸angular.d.ts
最终守则:
public saveTechnicianNote = (jobNumber: string, technicianNote: Model.TechnicianNote): ng.IPromise<any> => {
var data = {
jobNumber: jobNumber,
subject: technicianNote.subject,
details: technicianNote.details
};
return this.$http.post(this.urlFactory.saveTechnicianNote, data);
}