pbastowski / angular2-now

Angular 2 @Component syntax for Angular 1 apps
MIT License
145 stars 15 forks source link

Inject(['$foobar']) in this.$injected.$foobar #30

Closed hlehmann closed 8 years ago

hlehmann commented 8 years ago

An idea in order to make injections available in prototype's methods.

pbastowski commented 8 years ago

I'm not sure what the idea is. Could you elaborate on how this would work and provide some code examples. Thanks.

hlehmann commented 8 years ago

Yes of course, something like that.

@Component(...)
@Inject(['$scope', '$state', ...])
class MyComponent {
  constructor() {
  }

  onClick() {
    let $state = this.$injected.$state;
    $state.go('page2');
  }
}
pbastowski commented 8 years ago

Thanks for your example. It's clear to me now what you're asking.

Consider the example below:

@Component(...)
@Inject('$scope', '$state')  //  no need to use array notation
class MyComponent {
  constructor (private $scope, private $state) {
  }

  onClick() {
    this.$state.go('page2');
  }
}

The above syntax is TypeScript. Could you use TypeScript instead of Babel? It's a drop in replacement for Babel in most cases. No need to learn anything new and no requirement to declare types anywhere, as they are completely optional.

In TypeScript, the private keyword automatically puts the argument on this. So,

constructor(private $scope) { }

is equivalent to ES6

constructor($scope) { 
    this.$scope = $scope;
}

I could implement what you ask, but it's not what Angular2 does and it's already solved with TypeScript (if you can use it).

kamilkisiela commented 8 years ago

@hlehmann I have class to do that. I can publish it if you want.

Example:

@Component(...)
@Inject(['$scope', '$state', ...])
class MyComponent extends AssignInjectables {
  constructor() {
    super(arguments);
  }

  onClick() {
    let $state = this.$state;
    $state.go('page2');
  }
}
pbastowski commented 8 years ago

Nicely done. Angular-meteor also uses such an approach to provide reactive extensions, for example.

However, using extends with a utility parent class "eats up" your ability to extend from other classes. It may not be a problem this time, but I have experienced such a problem myself recently. Just something to think about.

pbastowski commented 8 years ago

Since this is not a bug and I don't plan to implement this feature in angular2-now, I will close this issue. We could, however, create a wiki and add a reference to this there.