【问题标题】:Is it possible to create a Component abstraction on Angular 2?是否可以在 Angular 2 上创建组件抽象?
【发布时间】:2016-01-12 19:33:13
【问题描述】:

我想创建一个具有初始行为的 AbstractComponent,同时能够在需要时在子级上覆盖它,这可能吗?这是一个好习惯吗?

应该或多或少是这样的:

export abstract class AbstractComponent implements OnInit {

  constructor(authService: AuthService, router: Router) {}

  ngOnInit() {
    if (authService.userNotLoggedInAnymore()) {
      router.navigate(['Login']);
    }
  }

  ...
}

【问题讨论】:

  • 您在使用这种方法时遇到问题了吗?
  • 我想知道如何为 Authservice 和 Router 指定提供者,因为我不能使用 @Component 注释,主要是因为它没有模板。这让我想知道 Angular 2 是否是为此设计的目的
  • 我猜您无论如何都会在bootstrap() 中指定此类提供程序,而不是在每个组件上。如果你想要一个单例,你必须只在bootstrap() 中传递它,否则会为每个组件创建一个新实例。
  • 哦,真的吗?这对我来说是新的:O
  • 只有您真正想要为每个组件创建一个新实例的提供者才应在@Component(providers: []) 中列出。

标签: angular architecture abstraction


【解决方案1】:

是的,只需使用真正的@Component 扩展该类并在您覆盖的方法中调用super(),例如ngOnInit。而且您还必须在父级中覆盖至少具有相同或更多依赖项的构造函数,并使用super() 传递它们。

【讨论】:

  • 模板怎么样,也可以和父抽象组件嵌套?
  • 组件继承不包括模板和样式。
  • 我在使用 --aot 构建 Angular 4 应用程序时遇到错误:“无法确定 [file] 中类 [MyComponent] 的模块中的错误!将 [MyComponent] 添加到 NgModule 以修复它。”有人有解决方法吗?
  • 遇到与@Algis 相同的问题 - 有人最终找到解决方法吗?
【解决方案2】:

作为替代方案,您也可以在抽象类中完全不使用构造函数参数,并使用 @Inject 装饰器声明服务,那么您就不需要触摸继承类的构造函数并在那里调用 super(...) 方法:

import { Inject } from '@angular/core';

export abstract class AbstractComponent implements OnInit {

  @Inject(AuthService) private authService: AuthService;
  @Inject(Router) private router: Router;

  ngOnInit() {
    if (authService.userNotLoggedInAnymore()) {
      router.navigate(['Login']);
    }
  }
  ...
}

【讨论】:

    【解决方案3】:

    这可能有点晚了,但我为那些正在接受的人找到了解决方法

    ERROR in Cannot determine the module for class [MyComponent] in [file]!
    Add [MyComponent] to the NgModule to fix it.
    

    使用 AOT 构建时。 将组件添加到 declaration 部分时,尝试使用 <any> 进行转换,例如<any>MyComponent。 这听起来不太干净,但至少它对我有用。 如果有人碰巧找到更好的解决方案,请分享:)

    【讨论】:

    • 感谢您的来电!以为这是不行的,直到我看到你的评论。谢谢!
    猜你喜欢
    • 2012-11-18
    • 1970-01-01
    • 2021-10-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-24
    • 2020-06-22
    • 1970-01-01
    相关资源
    最近更新 更多