【问题标题】:why modules can have methods to be used?为什么模块可以有方法可以使用?
【发布时间】:2019-11-28 00:33:10
【问题描述】:

我是 Angular 的新手,还在努力理解模块。

我看到一本书的代码如下:

import { Routes, RouterModule } from "@angular/router";

const routes: Routes = [{ path: "form/edit", component: FormComponent }]

export const routing = RouterModule.forRoot(routes);

作者说:

forRoot 方法生成一个包含路由服务的模块

我很困惑,如何使用一个模块来访问像forRoot 这样的函数,模块不只是声明要使用的组件/指令吗? CustomModule.CustomMethod() 怎么用?

例如,定义一个模块的模板是:

import ...

@NgModule({
 imports: [BrowserModule...],
 declarations: [AppComponent...],
 providers: [...]
})
export class AbcModule { }      //where can I define static CustomMethod?

没有可以在 AbcModule 中使用的静态方法的定义:

AbcModule.CustomMethod()

【问题讨论】:

  • forRootRouterModule 中的一个静态 方法。如果你在自己的模块中声明一个静态方法,你可以用同样的方式调用它。
  • @R.Richards 感谢您的回答。那么如何在模块中声明静态方法呢?
  • 基本上就是这样:static forRoot(): ModuleWithProviders { return { ngModule: AbcModule }; }angular.io/guide/ngmodule-faq#what-is-the-forroot-method。这在构建用于其他项目的库时很有用。
  • @R.Richards 你的意思是静态方法需要在 AbcModule 内部进行微调,就像在普通类中定义静态方法一样?
  • 是的。请参阅我发布的这个旧答案:stackoverflow.com/questions/50534543/…。可以帮助您了解它在真实情况下的样子。

标签: angular


【解决方案1】:

模块只是一个“普通”类,带有@NgModule 注释。 所以它没有理由不能有方法,包括像 forRoot() 这样的静态方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-18
    • 2015-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-27
    相关资源
    最近更新 更多