“尝试在Angular 5中引导多个组件时找到引导代码,但不能”,但它有用吗?

时间:2018-02-21 07:58:07

标签: angular angular5 angular-bootstrap

所以我遇到了一个非常非常奇怪的问题。我正在尝试在Angular 5项目中引导多个组件,所以我可以这样做:

<body>
    <awesome-component></awesome-component>
    <cool-component></cool-component>
</body>

它运行正常,但是有一个问题:我无法使用main.ts文件中的多个模块构建项目,除非我ng build --watch并且之后添加第二个模块 。这非常奇怪。

看看这两个模块:

AwesomeModule

import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";

import { AwesomeComponent } from "./awesome.component";

@NgModule({
    declarations: [AwesomeComponent],
    imports: [BrowserModule],
    bootstrap: [AwesomeComponent]
})
export class AwesomeModule {}

CoolComponent

import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";

import { CoolComponent } from "./cool.component";

@NgModule({
    declarations: [CoolComponent],
    imports: [BrowserModule],
    bootstrap: [CoolComponent]
})
export class CoolModule {}

如果我在main.ts内引导这些:

platformBrowserDynamic().bootstrapModule(AwesomeModule);
platformBrowserDynamic().bootstrapModule(CoolModule);

运行ng build时出现此错误:

ERROR in Error: Tried to find bootstrap code, but could not. Specify either statically analyzable bootstrap code or pass in an entryModule to the plugins options.
    at Object.resolveEntryModuleFromMain (C:\test\node_modules\@ngtools\webpack\src\entry_resolver.js:121:15)
    at Promise.resolve.then.then (C:\test\node_modules\@ngtools\webpack\src\angular_compiler_plugin.js:241:54)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)

如果我像这样删除其中一个:

platformBrowserDynamic().bootstrapModule(AwesomeModule);
// platformBrowserDynamic().bootstrapModule(CoolModule);

然后我再次运行ng build,它运行正常。 以下是奇怪的部分:如果我将--watch添加到ng build,它将侦听文件更改并构建受影响的文件。如果我使用 ONE 模块运行ng build --watch,它运行正常(正如我之前所说),但如果我然后添加第二个模块(删除注释),它构建并正常工作

所以问题是,我根本无法使用ng build从头开始构建,而我的main.ts文件中有两个模块(包含两个组件)。

之前有其他人遇到过此问题吗?我搞砸了什么吗?

这是我的一个组件,只是为了衡量标准:

cool.component.ts

import { Component } from "@angular/core";

@Component({
    selector: "cool-component",
    templateUrl: "./cool.component.html"
})
export class CoolComponent {
    public title = "Cool stuff";
}

1 个答案:

答案 0 :(得分:-1)

来自https://angular.io/guide/architecture

&#34; bootstrap - 主应用程序视图,称为根组件,托管所有其他应用程序视图。只有root模块才能设置此引导属性。&#34;

你可以创建一个app-root并输入这个app-root的html

//index.html
<body>
<app-root>
</body>

//app-root.component.html
<awesome-component></awesome-component>
<cool-component></cool-component>
相关问题