angular - 在 Angular(4) 中使用拆分应用程序模块进行导入(客户端、服务器、共享)

标签 angular .net-core

我使用 yeoman 生成器为前端创建了一个 .net spa 应用程序。它创建一个包含三个 app.module.ts 文件(app.module.client.ts、app.module.shared.ts、app.module.server.ts)的应用程序。不幸的是,位于客户端应用程序模块文件中的 NgModule 导入似乎没有正确注入(inject)到组件中。因此,当我尝试在输入上使用 ngFor 时,出现错误“无法绑定(bind)到‘ngModel’,因为它不是‘输入’的已知属性。”我认为这是因为表单模块没有被导入,即使我的 app.module.client.ts 文件如下所示: 从'@angular/core'导入{NgModule};

import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { sharedConfig } from './app.module.shared';
import {SelectModule} from 'ng2-select';

    @NgModule({
        bootstrap: sharedConfig.bootstrap,
        declarations: sharedConfig.declarations,
        imports: [
            BrowserModule,
            FormsModule,
            HttpModule,
            SelectModule,
            ...sharedConfig.imports
        ],
        providers: [
            { provide: 'ORIGIN_URL', useValue: location.origin }
        ]
    })
    export class AppModule {
    }

也许我遗漏了一些关于这些划分模块如何工作的信息。考虑到这种不同的模块架构,如何正确导入模块?

更新:我也能够通过将模块导入包含在 app.module.server.ts 中来解决问题。我想保留这个问题,希望有人能解释它是如何工作的。这尤其奇怪,因为 Yeoman 的预构建模板在 app.module.client.ts 文件中导入了所有模块,并且在使用 dotnet run 运行网站时它们似乎无能为力,它们必须在服务器中复制文件也是如此。

最佳答案

ASP.NET Core SPA with Angular 4 模板将 AppModule 拆分为三个文件,以便 Webpack 能够高效地编译客户端包(适合在浏览器中运行)和服务器端预渲染包(用于在 Node 中运行)。

更具体地说,这种方法期望:

  • 特定于浏览器的模块和提供程序将放入 app.module.browser.ts 文件中。

  • 服务器特定的模块和提供程序将放入 app.module.server.ts 文件中。

  • 无论执行上下文如何,所需的任何内容都将放入 app.module.shared.ts 文件中。

这将允许两种不同的引导周期:一种用于浏览器(共享 + 浏览器),一种用于服务器(共享 + < em>服务器)。两者之间的主要区别在于,第一个从 @angular/platform-b​​rowser 包导入 BrowserModule,而后者导入 ServerModule > 来自 @angular/platform-server 包 - 这是从服务器渲染 Angular 应用程序页面所必需的。

也就是说,您应该将所有应用程序引用放入 app.module.shared.ts 文件中,并使用同构 方法编写 Angular 代码 - 这意味着它无论执行上下文如何,其余的都应该由模板附带的默认 Webpack 配置来处理,这将为 JIT、AoT 和服务器端渲染生成适当的客户端和服务器构建。

有关如何开始在 Angular 中编写同构代码和/或识别执行环境并做出相应 react 的一些(非常)基本信息,请查看 this blog post我就这个主题写的。

关于angular - 在 Angular(4) 中使用拆分应用程序模块进行导入(客户端、服务器、共享),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45788487/

相关文章:

angular - 如何使用 Ionic Native Storage 存储数组数据?

angular -/node_modules/moment-timezone/index.d.ts (47,77) : ';' expected. 中出现错误如何修复

angular - 无效管道参数 : '' for pipe 'AsyncPipe' at invalidPipeArgumentError

ubuntu - .net core web api访问容器中的文件夹

c# - 从另一个项目添加 ApiAuthorizationDbContext 迁移 - EF Core

c# - 如何使 [DisallowNull] 显示对象初始值设定项错误?

c# - 更改 DateTime 的时区以满足 API 契约(Contract)

c# - 为什么 System.Text Json Serializer 不会序列化这个通用属性,但 Json.NET 会?

javascript - 自定义验证不禁用表单提交按钮 - Angular 5

asp.net - (TS) In 'const' enum declarations member initializer must be constant expression