angular 1.5 component and babel

2019-08-15 05:18发布

问题:

so, I'm trying to use the 1.5 component feature, but coding with fat arrows. I am using babel to build the system

My component, stripped down to the bare minimum to show my problem, is thus:

angular.module('myApp')
  .component('myComponent', {
        controller: () => {
            this.$onInit = () => {};
        },

        template: `<p>foobar1</p>`
    });

when I try and load this component, I get an error complaining about

typeError: Cannot set property '$onInit' of undefined

so, when I look at the sources in chrome devtools, I see

angular.module('myApp').component('myComponent', {
/** @ngInject */
controller: function controller() {
    undefined.$onInit = function () {};
},
template: '<p>foobar1</p>'

});

I would expect that I have done something very wrong, but can't see it ;)

anyone got any tips ?

thanks

回答1:

Angular creates new instantion of controller for every component. In ES5 we dont have classes, so we pass construction function here.

But in es6 we have class, so you can use it instead

let myComponent = {
    controller: myComponentController,
    template: `<p>foobar1</p>`
};

class myComponentController{
  constructor() {
    this.answer = 41;
  }
  $onInit() {
    this.answer++;
  }
};

angular.module('myApp')
  .component('myComponent', myComponent);

Pascal has also written something about it here: http://blog.thoughtram.io/angularjs/es6/2015/01/23/exploring-angular-1.3-using-es6.html