5

我对 Angular 1 的最大问题是扩展(在面向对象的意义上)指令是多么困难。

例如,input[number]在我的自定义小部件上重用指令几乎是不可能的,我必须重新实现所有验证和类型转换代码。

Angular 2 组件被实现为类,因此它们似乎可以轻松扩展。但是,他们也有@Component带有非常具体的选择器等的注释,这让我不清楚这些是否可以完全覆盖。

那么 Angular 2 指令实际上是可扩展的吗?

编辑:

好的,“可扩展”不一定是扩展类。它可以创建一个由多个现有指令组成的新指令。我对这种方法的问题是应用子指令的机制是什么?

(这些@Component类不是传统的 OO 类,具有可以分派给子级的方法。它只是字段和回调的容器,完全由注释后面的任何内容驱动。)

4

1 回答 1

5

注释不是继承的,所以如果你有:

@Directive({
    selector:'foo',
    inputs:['bar']
})
export class Foo  {}


//no annotation
export class FooBar extends Foo {} //not a directive


@Directive({  
   selector:'foobaz' 
}) 
export class FooBaz extends Foo {} //is a directive, but has no inputs 

FooBar will not be recognized as a directive at all, and FooBaz will but it won't the bar input (or any others). So, if inheritance is really what makes the most sense for your use-case, the way to approach this would be to declare inputs etc. in the child class annotations and pass them as constructor arguments to the parent class, where you can encapsulate common functionality.

That said, I don't think extensibility necessarily implies inheritance, and in my experience the old adage "favor composition over inheritance" is doubly true when DI is involved.

Someone much smarter than me recently said, "inheritance will murder your children in their sleep", and I tend to adhere to that viewpoint myself unless I'm damn sure it's the right tool for my use-case.

于 2015-12-17T02:28:07.973 回答