【发布时间】:2017-05-06 01:48:22
【问题描述】:
所以我有一个服务调用到后端并保存一个对象,该调用设置了一个返回数字的承诺。
这个调用看起来像这样
saveTcTemplate(item: ITermsConditionsTemplate): ng.IPromise<number> {
item.modifiedDate = new Date();
return this.$http.post(this.api + '/SaveTcTemplate', item)
.then(this.returnData);
}
returnData = (response: any) => {
return response.data;
};
这是在创建新对象时,将所有字段设置为所需的值,传递以保存,然后调用以显示。
这是用于在对象保存后拉取对象的 get 函数。
getTermsConditions(id: number): ng.IPromise<ITermsConditionsTemplate> {
return this.$http.get(this.api + '/GetTermsConditions',
{
params: {
id: id
}
}).then(this.returnData);
}
这是对象的初始构造、保存和获取
this.newTemplate.copyId = 0;
this.newTemplate.id = 0;
this.newTemplate.isLibrary = true;
this.newTemplate.studyFacilityScheduleId = this.studyFacilityScheduleId;
this.studyTermsConditionsService.saveTcTemplate(this.newTemplate)
.then(this.studyTermsConditionsService.getTermsConditions)
.then(this.setTemplateData);
当这样设置时,我可以成功保存一个新项目,并将其 id(ng.IPromise 部分)返回给我,并传递给我的 Get 服务调用。
问题是,当以这种方式设置时,this.$http.get 返回未定义。从我认为我从其他类似的堆栈溢出问题中了解到的情况来看,它正在发生,因为我在调用该函数时没有明确地将任何内容传递给它的参数
.then(this.studyTermsConditionsService.getTermsConditions)
为了测试这一点,我还设置了保存并得到这样的结果
var data: any;
data = this.studyTermsConditionsService.saveTcTemplate(this.newTemplate);
this.studyTermsConditionsService.getTermsConditions(data)
.then(this.setTemplateData);
这确实奏效了。 $http.Get 被识别,并且可以使用,但是这个设置的问题是;由于 ng.IPromise 的异步特性,数据不会作为承诺的数值发送到我的 Get 函数。它以 $$promise 类型发送,这导致我的 get 函数中的参数为 NaN。
所以我传递一个可用值的一种方式,即 32,但我没有明确传递这个值,所以 $http.get 是未定义的。
另一种方式,我显式传递了一个参数,因此 $http.get 被识别并且可用,但是显式调用的参数是 $$promise 类型,而不是数字类型,不幸的是,ng.IPromise 似乎
我该如何从这里开始??
【问题讨论】:
标签: javascript angularjs asynchronous typescript