如何在组件的类定义中注入依赖项? [英] How do I inject a dependency in a class definition of a component?

查看:108
本文介绍了如何在组件的类定义中注入依赖项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个类定义的组件(稍后由webpack和babel转换回ES5).我需要在其中一种方法中使用$ http服务.我怎么做?我应该在哪里注入$ http作为依赖项?如果我在构造函数参数中执行此操作,则会收到一个错误,好像根本没有注入它一样.也许上课不是去这里的方法吗?

I have this class-defined component (transpiled later by webpack and babel back into ES5). I need to use the $http service in one of its methods. How do I do that? Where do I inject $http as a dependency? If I do it in the constructor arguments, I get an error as if I hadn't injected it at all. Maybe classes is not the way to go here?

angular.module('myApp').component('home', {
    template: require('./home.component.html'),
    controller: class HomeCtrl {
        constructor() {
        }
        doMe() {
            $http.get('http://www.yahoo.com/');
        }
    }
});

推荐答案

ES2015类(或转译类)只是原型继承的语法糖.这意味着将您定义的方法放在类"的原型上.为了能够访问注入到构造函数中的依赖项,您需要以某种方式存储它们,以供原型方法稍后引用.

ES2015 classes (or transpiled classes) are just syntactic sugar over prototypal inheritance. What this means is that the methods you define are put on the prototype of the "class". In order to be able to access the dependencies injected in the constructor, you need to somehow store them for later reference by the prototype method.

这通常是通过将它们放在实例上来完成的:

This is usually done by putting them on the instance:

function HomeController($http) {
  this.$http = $http;
}
HomeController.prototype.doMe = function() {
  this.$http.get('http://www.yahoo.com/');
};

在基于类的语法中,它转换为:

In class-based syntax this translates to:

class HomeController {
  constructor($http) {
    this.$http = $http;
  }

  doMe() {
    this.$http.get('http://www.yahoo.com/');
  }
}



如果使用TypeScript,则可以通过使用构造函数参数上的访问修饰符来保存一些样板.例如:



If you are using TypeScript, you can save some boilerplate by using access modifiers on the constructor arguments. E.g.:

class HomeController {
  constructor(private $http) {}
}

...的缩写:

class HomeController {
  private $http;

  contructor($http) {
    this.$http = $http;
  }
}



如果您想使控制器变得友好,可以使用此处(可能与 ngAnnotate 之类的工具一起使用).例如,这是您可以使用"$inject属性注释"方法的方式:


EDIT 2:
If you want to make your controller minification-friendly, you can use one of the options described here (possibly along with a tool like ngAnnotate). For example, this is how you could use the "$inject Property Annotation" method:

ES5

HomeController.$inject = ['$http'];
function HomeController($http) {...}
HomeController.prototype.doMe = function() {...}

ES2015

class HomeController {
  constructor($http) {...}

  doMe() {...}
}
HomeController.$inject = ['$http'];

// OR

class HomeController {
  static get $inject() { return ['$http']; }
  constructor($http) {...}

  doMe() {...}
}

TypeScript

class HomeController {
  static $inject = ['$http'];
  constructor(private $http) {}

  doMe() {...}
}

这篇关于如何在组件的类定义中注入依赖项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆