【问题标题】:How to get typescript to recognize a custom action on the angular $resource?如何让打字稿识别角度 $resource 上的自定义操作?
【发布时间】:2016-06-11 18:44:48
【问题描述】:

这是在打字稿中使用角度 $resource 的示例。在这个例子中,我试图在我定义的资源上创建一个更新操作,就像在https://docs.angularjs.org/api/ngResource/service/$resource 中所做的一样。我还返回了一个实例ng.resource.IResourceClass<IVenueResource>

module app.common {
    interface IVenueService{

    }
    export interface IVenueResource extends ng.resource.IResource<app.domain.IVenue>{
      update(IVenue: app.domain.IVenue) : app.domain.IVenue;
    }

    export class VenueService implements IVenueService{
      static $inject = ["$resource", "url"];
      constructor(private $resource: ng.resource.IResourceService, private url: URL_CONSTANTS){
      }

    getVenueResource(): ng.resource.IResourceClass<IVenueResource>{
      // Define custom action as IActionDescriptor
      var updateAction : ng.resource.IActionDescriptor = {
          method: 'PUT',
          isArray: false
      };
      return <ng.resource.IResourceClass<IVenueResource>>
      this.$resource(this.url.BASE_API+"/v1/venues/:id", {id: '@id'} ,{
        update: updateAction
      });
    }
  }
  angular
    .module("common.services")
    .service("venueService", VenueService);
}

现在是时候使用资源了,资源是由我的类实现的接口定义的。但我仍然得到一个错误,我如何让打字字典识别更新方法。

module app.Venue {

  interface INavigationScope{
    venueResource: ng.resource.IResourceClass<app.common.IVenueResource>;
  }

  class VenueListCtrl implements INavigationScope {
    venueResource: ng.resource.IResourceClass<app.common.IVenueResource>;
  }
  sample(){
    var updatedVenue =this.venueResource.update({id: 1, name: 'Amphitheather'},
       ()=> {});
  }
}

【问题讨论】:

    标签: javascript angularjs typescript angularjs-service


    【解决方案1】:

    很快从这个参考https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/angularjs/angular-resource.d.ts#L85意识到这一点

    我应该使用IResourceClass&lt;IResource&lt;T&gt;&gt; 来扩展我的界面,因为IResource&lt;T&gt; 没有添加自定义方法的选项。

    interface IResourceClass<T> {
            new(dataOrParams? : any) : T;
            get(): T;
            ...
    }
    

    此外,当使用自定义方法时,我需要分配正确的声明。

    interface INavigationScope{ venueResource: app.common.IVenueResource; }
    

    返回IVenueResourceClass 的一个实例,它是ng.resource.IResourceClass&lt;ng.resource.IResource&lt;app.domain.IVenue&gt;&gt; 的子对象,但使用update() 方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-17
      • 1970-01-01
      • 2016-01-20
      • 2020-05-30
      • 1970-01-01
      • 2019-04-09
      • 2013-08-16
      • 2019-04-17
      相关资源
      最近更新 更多