2016-09-08 7 views
2

以下は、これまでに私のコードです:
マイモジュール

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を取得し、他の場所にそれを使用してください。データサービスでは、メソッドを使用してデータベースからフォーマットを取得します。これは約束として返され、成功した場合はコントローラからgetAccountLabelFormat()メソッドを呼び出すと返される変数を設定しています。私の問題は、サービスメソッドが非同期であるため、getAccountLabelFormat()メソッドを呼び出すと、accountLabelFormatサービスの変数がまだ設定されていないため、コントローラで未定義の値が得られるたびに問題になります。どのように私はこれを解決することができますに関する任意のアイデア?前もって感謝します。

答えて

2

$q.whenを使用してください。例えばhttps://docs.angularjs.org/api/ng/service/ $ qを

をチェックアウト:あなたは、その値を求める際に

$q.when(this.accountLabelFormat) 

ので、それは約束を返します。その後、ちょうどそれ、私はわずかな違いでも同様のアプローチをしています、その後の文

+0

をチェーン。 '$ q.when() 'を使う代わりに、私は自分のサービスから' promise'を返し、最終的に価値を得るために私のコントローラの中で 'promise'を処理しました。とにかく助けてくれてありがとう:) –

関連する問題