以下是我的代码:
我的模块
module App.SomeModule {
import ILabelSettingsViewModel = App.GeneralSettings.data.ILabelSettingsViewModel;
import IGeneralSettingsService = App.GeneralSettingsService.IGeneralSettingsService;
export enum LabelPageFormat {
A4,
Thermal
}
export interface IConsignmentDataService {
getAccountLabelFormat(): LabelPageFormat;
}
export class MyDataService implements IMyDataService {
accountLabelFormat: LabelPageFormat;
static $inject: string[] = ["generalSettingsService"];
constructor(private generalSettingsService: IGeneralSettingsService) {
this.determineAccountLabelFormat();
}
getAccountLabelFormat(): LabelPageFormat {
return this.accountLabelFormat;
}
private determineAccountLabelFormat() {
var that = this;
this.generalSettingsService.getLabelSettings().then((data: ILabelSettingsViewModel) => {
switch (data.name) {
case LabelPageFormat[LabelPageFormat.Thermal]:
that.accountLabelFormat = LabelPageFormat.Thermal;
break;
default:
that.accountLabelFormat = LabelPageFormat.A4;
break;
}
}, () => {
that.accountLabelFormat = LabelPageFormat.A4;
});
}
}
angular.module("app.common").service("myDataService", MyDataService);
}
和我的控制器
module App.Consignment.List {
"use strict";
import IConsignmentDataService = Consignment.IConsignmentDataService;
import ConsignmentListGridScope = Consignment.IConsignmentListGridScope;
class ConsignmentListController implements IConsignmentBulkActionProvider {
accountLabelFormat: LabelPageFormat;
static $inject = ["$scope", "myDataService"];
constructor(private $scope: ConsignmentListGridScope, private myDataService: IMyDataService) {
this.accountLabelFormat = this.consignmentDataService.getAccountLabelFormat();
}
}
angular.module("app.consignment").controller("consignmentListController", ConsignmentListController);
}
我要做的是,从我的数据服务中获取accountLabelFormat,然后将其用于其他地方。在数据服务中,一个方法用于从数据库中获取格式,该格式作为promise返回,然后如果成功,我将设置从我的控制器调用getAccountLabelFormat()
方法时将返回的变量。现在我的问题是,因为服务方法是异步的,所以当我调用getAccountLabelFormat()
方法时,accountLabelFormat
服务中的变量尚未设置,所以每次我在我的服务器中得到一个未定义的值控制器。关于如何解决这个问题的任何想法?提前谢谢。
答案 0 :(得分:4)
使用$q.when
。看看https://docs.angularjs.org/api/ng/service/ $ q
例如:
$q.when(this.accountLabelFormat)
所以当你要求这个值时,它会返回一个promise,然后将它链接一个then语句