![](/img/trans.png)
[英]React/TypeScript: How should I handle this style of component composition?
[英]Angular and TypeScript: How should I handle this as
我有一個關於如何處理Angular異步調用的問題。
我正在從控制器的服務中調用以下兩個方法來獲取對象,即“ categoryInfo”
如何獲得以下方法來返回categoryInfo並正確打印它?
調用方(在控制器中)兩種方法↓
console.log(this.service.getLargeCategoryList()); ←※Prints out as "undefined"
方法1↓
public getLargeCategoryList(): any {
console.log('Inside getLargeCategoryList');
this.getCategoryInfoList('', ServiceUrls.URL_FOR_TOP_CATEGORY)
.then((data) => {
var categoryInfo: ILCategoryInfoRes[] = data.categoryInfo;
return categoryInfo; ←※Appears to be skipped
}, function (data) {
console.log(data);
alert('Error');
return null;
});
console.log('Coming out of getLargeCategoryList');
}
方法2↓
private getCategoryInfoList(parameter: any, serviceUrl: string): ng.IPromise<any> {
var def = this.qService.defer();
this.httpService({
method: 'POST',
url: serviceUrl,
data: parameter
}).success(function (data: any, status, headers, config) {
//Success
var categoryInfo: ILCategoryInfoRes[];
var statusInfo: IStatus[];
//categoryInfo = data.categoryInfo;
statusInfo = data.status;
if (statusInfo[0].statusCode == '000') {
def.resolve(data);
} else {
def.resolve(statusInfo);
}
}).error(function (data, status, headers, config){
//Error
def.reject("Failed");
});
return def.promise;
}
您將需要從此函數中返回承諾:
public getLargeCategoryList(): any {
console.log('Inside getLargeCategoryList');
return this.getCategoryInfoList('', ServiceUrls.URL_FOR_TOP_CATEGORY)
.then((data) => {
var categoryInfo: ILCategoryInfoRes[] = data.categoryInfo;
return categoryInfo; ←※Appears to be skipped
}, function (data) {
console.log(data);
alert('Error');
return null;
});
console.log('Coming out of getLargeCategoryList');
}
處理它,就好像它返回一個promise,而不是一個值,因為它是一個異步操作:
this.service.getLargeCategoryList()
.then((data) => {
console.log(data);
}):
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.