【问题标题】:Returning a strongly typed promiseValue from angular $modalInstance with TypeScript使用 TypeScript 从 angular $modalInstance 返回强类型的 promiseValue
【发布时间】:2015-11-30 19:57:51
【问题描述】:

TypeScript 新问题。我正在尝试从 Angular 的 $modalInstance 返回一个强类型的承诺。

我有类似的东西:

this.$modal.open(options).result.then(result => {
    Currently result is type 'any'.  
    How do I cast it or affect it to be of type MyType?  (see below)         
});


interface myType {
    a: string,
    b: number
}

result: myType;
...

$modalInstance.close(this.result)

【问题讨论】:

    标签: angularjs modal-dialog typescript angular-promise


    【解决方案1】:

    我实际上必须包装 $modal 和 $modalInstance 服务来获取类型 T。上面的答案(我最初尝试过)将不起作用,因为 $modalInstance 结果是类型“任何”的承诺。被包装的 $modalInstance 是一个 T 类型的承诺。

    module my.interfaces {
    
    export interface IMyModalService<T> {
        open(options: ng.ui.bootstrap.IModalSettings): IMyModalServiceInstance<T>;
    }
    
    export interface IMyModalScope<T> extends ng.ui.bootstrap.IModalScope {
        $dismiss(reason?: any): boolean;
        $close(result?: T): boolean;
    }
    
    export interface IMyModalServiceInstance<T> extends ng.ui.bootstrap.IModalServiceInstance {
        close(result?: T): void;
        dismiss(reason?: any): void;
        result: angular.IPromise<T>;
        opened: angular.IPromise<any>;
        rendered: angular.IPromise<any>;
    }
    

    【讨论】:

      【解决方案2】:
      this.$modal.open(options).result.then((result: myType) => {
          Now result is declared to be of your type        
      });
      

      【讨论】:

      • 虽然这可能会回答这个问题,但也应该解释一下这个问题是如何以及为什么解决的
      • 我实际上必须包装 $modal 和 $modalInstance 服务来获取类型 。上面的答案(我最初尝试过)将不起作用,因为模态结果返回类型为“any”的承诺。包装好的 $modal 返回一个 . 类型的承诺
      猜你喜欢
      • 2020-02-11
      • 2019-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-05
      • 1970-01-01
      • 1970-01-01
      • 2021-10-17
      相关资源
      最近更新 更多