我正在使用TypeScript编写Angular 1.x,并且我有一个负责加载数据的服务(DataService)。举一个简单的例子,它查询节点并返回一个节点。在界面中:
getNode(id: number): ng.IPromise<Node>;
和实施:
getNode(id: number) {
return this.ajaxService.getNode(id)
.then((result: ng.IHttpPromiseCallbackArg<Node>) => {
return new Node(result.data.ID, result.data.Name);
});
}
但是,我想介绍另一种存储这些结果的服务,如果我之前已经查询过它们就会返回它们。如下所示:
getNode(id: number) {
var loadedNode = this.storageService.nodes.filter(e => (e.ID == id));
if (loadedNode.length > 0) {
return loadedNode[0];
}
return this.ajaxService.getNode(id)
.then((result: ng.IHttpPromiseCallbackArg<Node>) => {
var n = new Node(result.data.ID, result.data.Name);
this.storageService.nodes.push(n);
return n;
});
}
然而,返回类型失败,因为它期望'ng.IPromise'而不仅仅是'Node'。如何包装'return loadedNode [0];'进入某种承诺返回类型而不是返回实际对象?
答案 0 :(得分:2)
您可以使用$q
-service:
getNode(id: number) {
var deferred = this.$q.defer();
var loadedNode = this.storageService.nodes.filter(e => (e.ID == id));
if (loadedNode.length > 0) {
// immediately resolve with the cached node
deferred.resolve(loadedNode[0]);
} else {
// else load through service
this.ajaxService.getNode(id)
.then((result: ng.IHttpPromiseCallbackArg<Node>) => {
var n = new Node(result.data.ID, result.data.Name);
this.storageService.nodes.push(n);
// resolve with the loaded node
deferred.resolve(n);
});
}
// return the promise to register callbacks
return deferred.promise;
}
用法:
myService.getNode(id).then((node) => {
// success
}, () => {
// error
});
答案 1 :(得分:1)
使用$ q.when(value,[successCallback],[errorCallback],[progressCallback])
您可以使用
更改返回行return $q.when(loadedNode[0]);
的更多信息