我有一个关于如何处理Angular异步调用的问题。
我在一个服务器中调用以下两个方法来获取一个对象,即“categoryInfo”
如何让以下方法恢复categoryInfo并正确打印?
来电(在控制器中)两种方法↓
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');
}
方法1↓
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;
}
方法2↓
{{1}}
答案 0 :(得分:0)
您需要从此功能中退回承诺:
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);
}):