下面是我目前的代码:
我的模块
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);
}
和我的 Controller
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()
方法时返回的变量我的 Controller 。现在我的问题是,由于服务方法是异步的,当我调用 getAccountLabelFormat()
方法时,accountLabelFormat
服务中的变量尚未设置,因此每个时间我在我的 Controller 中得到一个未定义的值。关于如何解决这个问题的任何想法?提前致谢。
最佳答案
使用$q.when
。查看https://docs.angularjs.org/api/ng/service/ $q
例如:
$q.when(this.accountLabelFormat)
所以当你请求那个值时,它会返回一个 promise,然后将它链接到一个 then 语句
关于javascript - 如何在不使用 $scope $watch 的情况下等到变量被定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39381290/