【问题标题】:How can I modify the interface for $http in AngularJS?如何在 AngularJS 中修改 $http 的接口?
【发布时间】:2015-10-22 03:39:27
【问题描述】:

在我的应用程序调用中,我的代码如下所示:

            $http({
                url: '/abc'
                method: "PUT",
                ignoreLoadingBar: true
            })

这是一个正常的 $http 调用,但由于我使用的是 angular-loading-bar,所以添加了一个附加参数。

Typescript 将此标记为如下错误:

Severity    Code    Description Project File    Line
Error   TS2345  Argument of type '{ url: string; method: string; ignoreLoadingBar: boolean; }' is not assignable to parameter of type 'IRequestConfig'.
  Object literal may only specify known properties, and 'ignoreLoadingBar' does not exist in type 'IRequestConfig'.

我明白为什么它会显示错误,但我想做的是允许这个附加参数。我想做这样的事情:

interface IRequestConfigPlus extends ng.IRequestConfig {
  ignoreLoadingbar: boolean
}

有人能告诉我有没有办法让 $http 不会出现打字错误?如果可能的话,我想在不进入并修改 AngularJS 代码中的 IResponseConfig 接口的情况下解决这个问题。

更新

Basarat 提出了一个很好的建议,但我仍然不确定如何使用该界面,这是我的问题的一部分。那么问题是如何在这里使用 IRequestConfigPlus?

【问题讨论】:

    标签: javascript angularjs interface typescript


    【解决方案1】:

    这个最小的例子对我有用:

    ///<reference path="typings/angularjs/angular.d.ts" />
    
    let $http:ng.IHttpService = null;
    
    declare module angular
    {
        interface IRequestConfig {
            ignoreLoadingBar: boolean;
        }
    }
    
    $http({
        url: '/abc',
        method: "PUT",
        ignoreLoadingBar: true
    });
    

    【讨论】:

      【解决方案2】:

      有人能告诉我有没有办法让 $http 不会出现打字错误?

      这是因为对象新鲜度:https://basarat.gitbooks.io/typescript/content/docs/types/freshness.html

      快速解决方法:(use an assertion)

              $http({
                  url: '/abc'
                  method: "PUT",
                  ignoreLoadingBar: true
              } as ng.IRequestConfig)
      

      更好的修复

      为 angular-loading-bar 创建一个.d.ts 文件,为angular.IRequestConfig 接口添加其他属性。注:TypeScript interfaces are open ended

      【讨论】:

      • 谢谢。我确实尝试创建一个 IRequestConfigPlus.d.ts 文件,并且问题中提到了该接口。但我不确定如何使用它。我喜欢你对 as.ng.IRequestConfig 的想法。这和我把它放在前面一样吗?
      • 是的...一样
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-21
      • 1970-01-01
      • 2019-05-23
      • 1970-01-01
      • 2016-12-10
      • 1970-01-01
      相关资源
      最近更新 更多