【问题标题】:using $inject syntax with additional constructor arguments使用带有附加构造函数参数的 $inject 语法
【发布时间】:2014-11-06 20:34:06
【问题描述】:

在这里查看答案:https://stackoverflow.com/a/19272093/2547709

使用 $inject 语法,我的控制器最终看起来像这样:

class MyCtrl {

  public static $inject: string[] = ['$scope'];
  constructor($scope){
    // stuff
  }
}
// register the controller
app.controller("MyCtrl", MyCtrl);

我的问题是 - 如果我想将自己的自定义参数以及任何注入的变量传递给构造函数会发生什么?:

class MyCtrl {

  public static $inject: string[] = ['$scope'];
  constructor($scope, customArg){
    // stuff
  }
}
// Now how do I pass customArg in without it complaining?
app.controller("MyCtrl", MyCtrl(customArg)); // Nope

我觉得我错过了一些基本的东西,使用这种语法,你传递给 .controller() 函数的所有东西都必须用 angular 注册,所以我根本不应该尝试传递自定义参数?或者我可以传入任意值/对象吗?如果是这样怎么办?

【问题讨论】:

  • 你想通过什么例子?你能用 angular.value 用 angular 注册它吗?

标签: angularjs typescript


【解决方案1】:

自定义参数

如果 angular 要调用构造函数,则不能传入自定义参数。但是,您可以使用 Angular 注册其他内容,例如angular 将为您传递给控制器​​的服务、工厂、值(常量)。

更多:https://www.youtube.com/watch?v=Yis8m3BdnEM&hd=1

【讨论】:

  • 谢谢@basarat,我是你的视频的粉丝,他们真的帮助我掌握了如何以惯用的方式使用 typescript 和 angular 之类的东西!
  • 如果你有兴趣,我有一个新问题:here
  • @basarat:一个很好的例子是提供者,您将服务抽象为不同的类。现在的问题是,我想做吗?您将如何处理?
【解决方案2】:

对不起,我没有足够的积分来评论。

我有完全相同的情况,这是我的情况:

export abstract class DataService<T> {

    static $inject = ['$resource'];
    private svc: ng.resource.IResourceClass<ng.resource.IResource<T>>;

    constructor(
        protected $resource: ng.resource.IResourceService, url: string
    ) {
        this.svc = <ng.resource.IResourceClass<ng.resource.IResource<T>>>this.$resource(url, { id: '@id' });
    }

    public get(id: number): ng.IPromise<T> {
        return this.svc.get({ id: id }).$promise;
    }

}

export class MyDataService
    extends DataService<IItem> {


   // big problem here!!!
   constructor(
    ) {
        super("/api/items/:id");
    }

}

看起来我必须在每个派生类上重复注入,并且还要传入超级......所以多余

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-22
    • 2011-01-14
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    • 2017-08-02
    • 2011-10-08
    相关资源
    最近更新 更多