简体   繁体   English

Angular 2:找不到 NgModule 元数据

[英]Angular 2 : No NgModule metadata found

I'm brand new to Angular 2 and attempting to follow along with a video tutorial I found.我是 Angular 2 的新手,正在尝试按照我找到的视频教程进行操作。 Despite following all of the steps, Angular just won't work;尽管执行了所有步骤,Angular 还是无法正常工作; I get the following error:我收到以下错误:

compiler.umd.js:13854 Uncaught Error: No NgModule metadata found for 'App'.

and the component doesn't load at all.并且组件根本不加载。

Here are my files:这是我的文件:

package.json:包.json:

{
  "name": "retain",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "webpack --config webpack.spec.ts --progress --color && karma start",
    "start": "webpack-dev-server --inline --colors --progress --display-error-details --display-cached --port 3000  --content-base src"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@angular/common": "2.0.0",
    "@angular/compiler": "2.0.0",
    "@angular/core": "2.0.0",
    "@angular/forms": "2.0.0",
    "@angular/http": "2.0.0",
    "@angular/platform-browser": "2.0.0",
    "@angular/platform-browser-dynamic": "2.0.0",
    "@angular/router": "3.0.0",
    "core-js": "2.4.1",
    "lodash": "4.16.1",
    "rxjs": "5.0.0-beta.12",
    "zone.js": "0.6.25"
  },
  "devDependencies": {
    "@types/core-js": "0.9.33",
    "@types/lodash": "4.14.35",
    "@types/node": "6.0.39",
    "awesome-typescript-loader": "2.2.4",
    "css-loader": "0.23.1",
    "jasmine-core": "2.4.1",
    "karma": "1.1.1",
    "karma-chrome-launcher": "1.0.1",
    "karma-jasmine": "1.0.2",
    "karma-mocha-reporter": "2.0.4",
    "raw-loader": "0.5.1",
    "to-string-loader": "1.1.4",
    "ts-helpers": "1.1.1",
    "typescript": "2.0.2",
    "webpack": "1.13.1",
    "webpack-dev-server": "1.14.1"
  }
}

index.html:索引.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset=UTF-8>
    <title>Retain</title>
    <link rel="icon" href="data:;base64,iVBORw0KGgo=">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href='https://cdnjs.cloudflare.com/ajax/libs/normalize/4.1.1/normalize.min.css' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/flexboxgrid/6.3.0/flexboxgrid.min.css" type="text/css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons"
      rel="stylesheet">
    <link href="global.css" rel="stylesheet">
    <base href="/">
  </head>
  <body>

    <app>
      ... before angular loads.
    </app>

    <script src="polyfills.bundle.js"></script>
    <script src="vendor.bundle.js"></script>
    <script src="main.bundle.js"></script>

  </body>
</html>

main.ts:主.ts:

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module'; 

import { App } from './app/app';

const platform = platformBrowserDynamic();
platform.bootstrapModule(App);

platformBrowserDynamic().bootstrapModule(AppModule);

app.ts:应用程序:

import { Component } from '@angular/core';
import { NgModule }      from '@angular/core';

@Component({
  selector: 'app',
  template: `
    <div>
      <h3>
        Yo, world!
      </h3>
    </div>
    `
})

export class App {}

app.module.ts:应用程序模块.ts:

import { NgModule } from '@angular/core'; 
import { BrowserModule } from '@angular/platform-browser'; 
import { App } from './app'; 

@NgModule({ 
  imports: [BrowserModule], 
  declarations: [App], 
  bootstrap: [App] 
}) 

export class AppModule{}; 

Thanks for your time.谢谢你的时间。

I had this error even though I had everything that the answers above suggested in place.即使我拥有上述答案所建议的所有内容,我也遇到了这个错误。 A simple edit in the app.module.ts file ( like delete a bracket and put it back) did the trick.app.module.ts文件中进行一个简单的编辑(比如删除一个括号并将其放回原处)就成功了。

The problem is in your main.ts file.问题出在您的main.ts文件中。

const platform = platformBrowserDynamic();
platform.bootstrapModule(App);

You are trying to bootstrap App , which is not a real module.您正在尝试引导App ,这不是真正的模块。 Delete these two lines and replace with the following line:删除这两行并替换为以下行:

platformBrowserDynamic().bootstrapModule(AppModule);

and it will fix your error.它会修复你的错误。

尝试删除 node_modules rm -rf node_modules和 package-lock.json rm -rf package-lock.json ,然后运行npm install

After upgrading to Angular 6, I encountered the "ERROR in No NgModule metadata found for 'AppModule'."升级到 Angular 6 后,我遇到了"ERROR in No NgModule metadata found for 'AppModule'." with the angular-bootstrap-md package, which requires a tsconfig.json "include" as follows:使用 angular-bootstrap-md 包,它需要一个 tsconfig.json “include”,如下所示:

"include": ["node_modules/angular-bootstrap-md/**/*.ts", "src/**/*.ts"],

After days of troubleshooting and hair pulling, the solution was to arrange the list so that the app.module.ts was located first, under "src/**/*.ts".经过几天的故障排除和拉头发,解决方案是安排列表,使 app.module.ts 位于最前面,在“src/**/*.ts”下。 An Angular bug, perhaps?也许是一个 Angular 错误?

"include": ["src/**/*.ts","node_modules/angular-bootstrap-md/**/*.ts" ],

I genuinely hope this helps somebody, as I tried everything in this posting and nothing helped.我真的希望这对某人有所帮助,因为我尝试了这篇文章中的所有内容,但没有任何帮助。 After this change, everything compiles and works beautifully, as expected.在此更改之后,一切都按预期编译并运行良好。

The issue is fixed only when re installed angular/cli manually.仅当手动重新安装 angular/cli 时才能修复此问题。 Follow following steps.请按照以下步骤操作。 (run all command under Angular project dir) (在 Angular 项目目录下运行所有​​命令)

1)Remove webpack by using following command. 1) 使用以下命令删除 webpack。

npm remove webpack

2)Install cli by using following command. 2)使用以下命令安装cli。

npm install --save-dev @angular/cli@latest

after successfully test app, it will work :)成功测试应用程序后,它将起作用:)

if not then follow below steps.如果没有,请按照以下步骤操作。

1) Delete node_module folder. 1) 删除 node_module 文件夹。

2) Clear cache by using following command. 2) 使用以下命令清除缓存。

npm cache clean --force

3) Install node packages by using following command. 3) 使用以下命令安装节点包。

npm install

4)Install angular@cli by using following command. 4) 使用以下命令安装 angular@cli。

npm install --save-dev @angular/cli@latest

Note :if failed,try again :)注意:如果失败,请重试:)

5) Celebrate :) 5) 庆祝 :)

I would recommend restarting the application.我建议重新启动应用程序。 Most of the cases editor won't be able to detect the changes in the lazy loaded module.大多数情况下,编辑器将无法检测到延迟加载模块中的更改。

Late answer, but this might help someone.迟到的答案,但这可能对某人有所帮助。 I got the same error, tried out all the previously mentioned suggestions, banged my head against the wall, but nothing worked.我遇到了同样的错误,尝试了前面提到的所有建议,将我的头撞在墙上,但没有任何效果。

On careful observation, I noticed the following in app.module.ts:仔细观察,我注意到 app.module.ts 中有以下内容:

imports: [
  BrowserModule,
  BrowserAnimationsModule,
  FormsModule,
  HttpClientModule,, // Redundant comma 
  CoreModule
];

So I banged my head some more.所以我又敲了敲脑袋。 The extra comma, very innocently higlighted, by WebStorm, as a mild warning, wreaked havoc by inserting an empty slot in the Array.额外的逗号,非常无辜地被 WebStorm 突出显示,作为一个温和的警告,通过在 Array 中插入一个空槽来造成严重破坏。 Watchout fot the elision trap ;) WATCHOUT FOT的省音陷阱;)

There are more reasons for getting this error.出现此错误的原因还有很多。 This means your application failed to build as expected.这意味着您的应用程序未能按预期构建。

Check for the following..检查以下..

  • Check whether the node_modules version are not changed, this is the primary reason.检查 node_modules 版本是否没有改变,这是主要原因。
  • If you are moving from Some other Build tool to webpack, For example Systemjs to Webpack, If some of your dependencies are not modular in nature you may get this error, check for that too.如果您正在从其他构建工具迁移到 webpack,例如 Systemjs 到 Webpack,如果您的某些依赖项本质上不是模块化的,您可能会收到此错误,也请检查一下。
  • Check for Obsolete features of the framework, Ex: "HTTP_PROVIDERS" in angular 2 and remove them.检查框架的过时功能,例如:angular 2 中的“HTTP_PROVIDERS”并将其删除。
  • If you are upgrading, then make sure you are following the current syntax of the Framework, for Ex: routing syntax has been changed in Angular2..如果您正在升级,请确保您遵循框架的当前语法,例如:Angular2 中的路由语法已更改..
  • Check the Bootstraping process and make sure you are loading the correct Module.检查引导过程并确保您正在加载正确的模块。

In your main.ts , you are bootstrapping both your AppModule and your App.在您的main.ts ,您正在引导您的 AppModule您的应用程序。 It should just be the AppModule, which then bootstraps the App.它应该只是 AppModule,然后引导应用程序。

If you compare your main.ts to the docs you'll see the difference - just remove all references to App from main.ts如果您将 main.ts 与文档进行比较,您会看到不同之处 - 只需从 main.ts 中删除对 App 的所有引用

With Angular 5, I solved a similar problem by ugrading to @angular/cli 1.6.1 from 1.5.5:使用 Angular 5,我通过从 1.5.5 升级到@angular/cli 1.6.1 解决了类似的问题:

"devDependencies": {
  "@angular/cli": "1.6.1"
}

During ng serve the error I got was:ng serve期间,我得到的错误是:

ERROR in Error: No NgModule metadata found for 'AppModule'.
    at NgModuleResolver.resolve (/path/to/project/app/node_modules/@angular/compiler/bundles/compiler.umd.js:20247:23)

I had the same problem and couldn't solve it after reading all the above answers.我遇到了同样的问题,阅读上述所有答案后无法解决。 Then I noticed that an extra comma in declarations was creating a problem.然后我注意到声明中的额外逗号造成了问题。 Removed it, problem solved.删除了,问题解决了。

@NgModule({
    imports: [
        PagesRoutingModule,
        ThemeModule,
        DashboardModule,
    ],
    declarations: [
        ...PAGES_COMPONENTS,
        **,**
    ],
})

Hope it can help.希望它能有所帮助。 In my case, I work with lazy-load module and I found this mistake lead to ERROR in No NgModule metadata found for 'MyModule'.就我而言,我使用延迟加载模块,我发现这个错误会导致ERROR in No NgModule metadata found for 'MyModule'.

in app-routing.module.ts
{ path: 'mc3', loadChildren: 'app/module/my/my.module#MxModule' },

If I run ng serve --aot chrome dev tool can tell me Error: Cannot find 'Mc4Module' in 'app/module/mc3/mc3.module'如果我运行ng serve --aot chrome dev 工具可以告诉我Error: Cannot find 'Mc4Module' in 'app/module/mc3/mc3.module'

If you are having this issue in Angular 8 or Angular 9 (like I was), after:如果您在 Angular 8 或 Angular 9 中遇到这个问题(就像我以前一样),在:

  • Clearing your npm cache清除 npm 缓存
  • reinstalling all node_modules重新安装所有 node_modules
  • checking your "include" and "files" tsconfig setting etc检查您的“包含”和“文件”tsconfig 设置等

and you're still having issues, and you are Lazy Loading Modules check your angularCompilerOptions in your tsconfig.json or tsconfig.app.json , and make sure that "strictMetadataEmit" is set to false or is removed.而你仍然有问题,你是延迟加载模块的检查angularCompilerOptionstsconfig.jsontsconfig.app.json ,并确保“strictMetadataEmit”设置为false,或者被删除。

"angularCompilerOptions": {
    "preserveWhitespaces": false,
    "strictInjectionParameters": true,
    "fullTemplateTypeCheck": true,
    "strictTemplates": true,
    // "strictMetadataEmit": true <-- remove this setting or set to false
},

The setting is to help library creators which should never have lazy loaded modules built in. I had previously (using Angular 7) set all "strict" options to true...该设置是为了帮助永远不应该内置延迟加载模块的库创建者。我以前(使用 Angular 7)将所有“严格”选项设置为 true...

I had this issue when i cloned from a git repository and I had it resolved when I created a new project and re-inserted the src folder from the old project.当我从 git 存储库克隆时遇到了这个问题,当我创建一个新项目并从旧项目重新插入 src 文件夹时,我解决了这个问题。

The src folder is the only folder needed when deploying your angular application but you must reconfigure the dev environment, using this solution. src 文件夹是部署 angular 应用程序时唯一需要的文件夹,但您必须使用此解决方案重新配置开发环境。

you need to enable the ngModel directive.您需要启用 ngModel 指令。 This is done by adding the FormsModule to the imports[] array in the AppModule.这是通过将 FormsModule 添加到 AppModule 中的 import[] 数组来完成的。

You then also need to add the import from @angular/forms in the app.module.ts file: import { FormsModule } from '@angular/forms';然后,您还需要在 app.module.ts 文件中添加来自 @angular/forms 的导入: import { FormsModule } from '@angular/forms';

I finally found the solution.我终于找到了解决方案。

  1. Remove webpack by using following command.使用以下命令删除 webpack。
npm remove webpack
  1. Install cli by using following command.使用以下命令安装 cli。
npm install --save-dev @angular/cli@latest

after successfully test app, it will work :)成功测试应用程序后,它将起作用:)

If not then follow below steps:如果没有,请按照以下步骤操作:

  1. Delete node_module folder.删除 node_module 文件夹。
  2. Clear cache by using following command.使用以下命令清除缓存。
npm cache clean --force
  1. Install node packages by using following command.使用以下命令安装节点包。
npm install
  1. Install angular@cli by using following command.使用以下命令安装 angular@cli。
npm install --save-dev @angular/cli@latest

Note: If failed, try step 4 again.注意:如果失败,请重试步骤 4。 It will work.它会起作用。

I just had the same issue with a lazy-loaded module.我只是在延迟加载模块上遇到了同样的问题。 It turns out that the name of the module was incorrect.事实证明,模块的名称不正确。

Check the names of all your modules for possible typos.检查所有模块的名称以查找可能的拼写错误。

We've faced this issue on Angular Cli 1.7.4 at times.我们有时会在 Angular Cli 1.7.4 上遇到这个问题。 Initially we've got最初我们有

Cannot read property 'config' of null
TypeError: Cannot read property 'config' of null

And fixing this lead to the above issue.解决这个问题会导致上述问题。

We've removed package-lock.json我们已经删除了 package-lock.json

npm remove webpack

npm cache clean --force

You can also remove your node_modules folder.您还可以删除 node_modules 文件夹。 And then clean the cache.然后清理缓存。 re-installed angular cli:重新安装角cli:

npm install @angular/cli@1.7.4

And then you can do npm install again, just to make sure if everything is installed.然后您可以再次执行 npm install ,以确保是否安装了所有内容。

Then run然后运行

npm ls --depth 0

To make sure if all your node_modules are in sync with each other.确保您的所有 node_modules 是否彼此同步。 If there are any dependency mismatching, this is the opportunity for us to figure out.如果有任何依赖不匹配,这是我们弄清楚的机会。

Finally run npm start/ng serve.最后运行 npm start/ng serve。 it should fix everything.它应该解决一切问题。

This is out cheat code that we'll follow if we run into any issues with cli, before we dig deeper.这是在我们深入挖掘之前,如果遇到任何 cli 问题,我们将遵循的作弊代码。 95% of times it fixes all the issues. 95% 的情况下它可以解决所有问题。

Hope that helps.希望有帮助。

In my case, I was trying to upgrade my angular 6 project using ng update after that the entire universe collapse.就我而言,在整个宇宙崩溃之后,我试图使用ng update升级我的 angular 6 项目。

I was trying to update my project using this commands:我试图使用以下命令更新我的项目:

  • ng update @angular/cli ng更新@angular/cli
  • ng update @angular/core ng更新@angular/core
  • ng update @angular/material ng更新@angular/material

And then I found a problem with rxjs package and I run also this command.然后我发现 rxjs 包有问题,我也运行了这个命令。 - npm install --save rxjs - npm install --save rxjs

And then I get the error然后我得到了错误

No NgModule metadata found未找到 NgModule 元数据

I solve this by deleting my node_modules folder in the project root and then I run:我通过删除项目根目录中的node_modules文件夹来解决此问题,然后运行:

  • npm install安装

That's is, all works nice.也就是说,一切正常。

I found that the cause of this problem in my case, was that I've combined my Angular app with a node.js application in the same source tree, and in the root tsconfig.json I had:我发现在我的情况下这个问题的原因是我已经将我的 Angular 应用程序与同一源代码树中的 node.js 应用程序组合在一起,并且在根tsconfig.json我有:

"files": [ "./node_modules/@types/node/index.d.ts" ]

I changed this to我把这个改成

"compilerOptions": { "types": ["node"] }

And then to prevent node types being uses in your angular app, add this to tsconfig.app.json :然后为了防止在您的 angular 应用程序中使用节点类型,请将其添加到tsconfig.app.json

"compilerOptions": { "types": [] }

I had the same problem but none of all those solutions worked for me.我遇到了同样的问题,但所有这些解决方案都不适合我。 After further investigation, I found out that an undesired import was in one of my component.经过进一步调查,我发现我的一个组件中存在不需要的导入。

I use setTimeout function in app.component but for any reason Visual Studio added import { setTimeout } from 'timer';我在 app.component 中使用setTimeout函数,但出于任何原因,Visual Studio 添加了import { setTimeout } from 'timer'; where it was not needed.不需要的地方。 Removing this line fixed the issue.删除此行解决了问题。

So remember to check your imports before going further.因此,请记住在继续之前检查您的进口。 Hope it may help someone.希望它可以帮助某人。

I've encountered this problem twice now.我现在遇到过两次这个问题。 Both times were problems with how I was implementing my lazy loading.两次都是我如何实现延迟加载的问题。 In my routing module I had my routes defines as:在我的路由模块中,我的路由定义为:

  {
    path: "game",
    loadChildren: () => import("./game/game.module").then(m => {m.GameModule})
  }

But this is wrong.但这是错误的。 After the second => you don't need curly braces.在第二个 => 之后,您不需要花括号。 it should look like this:它应该是这样的:

  {
    path: "game",
    loadChildren: () => import("./game/game.module").then(m => m.GameModule)
 }

This error says necessary data for your module can't be found.此错误表示找不到模块的必要数据。 In my case i missed an @ symbol in start of NgModule.就我而言,我在 NgModule 的开头错过了一个@符号。

Correct NgModule definition:正确的 NgModule 定义:

 @NgModule ({ 
    ... 
 })
 export class AppModule {

 }

My case (Wrong case) :我的情况(错误的情况):

NgModule ({ // => this line must starts with @
   ... 
})
export class AppModule {

}

我遇到了同样的问题,我通过关闭编辑器(即Visual Studio Code )解决了它,再次启动它,运行ng serve并且它起作用了。

就我而言,我在我的一个组件中定义了几个(私有)静态方法,并在同一个组件中使用它们。

If Nothing else works try following如果没有其他工作,请尝试以下

if (environment.production) {
        // there is no need of this if block, angular internally creates following code structure when it sees --prod
        // but at the time of writting this code, else block was not working in the production mode and NgModule metadata
        // not found for AppModule error was coming at run time, added follow code to fix that, it can be removed probably 
        // when angular is upgraded to latest version or if it start working automatically. :)
        // we could also avoid else block but building without --prod saves time in building app locally.
        platformBrowser(extraProviders).bootstrapModuleFactory(<any>AppModuleNgFactory);
    } else {
        platformBrowserDynamic(extraProviders).bootstrapModule(AppModule);
    }

For me, the problem was that I had created a method named hasOwnProperty(obj, prop) in a Angular component.对我来说,问题是我在 Angular 组件中创建了一个名为hasOwnProperty(obj, prop)的方法。 The solution for me was deleting or renaming the method我的解决方案是删除或重命名该方法

In my case it was related to the AppModule importing two other modules:在我的例子中,它与导入另外两个模块的AppModule有关:

imports: [
    AModule,
    BModule
]

where AModule itself was already importing BModule .其中AModule本身已经在导入BModule

Removing BModule from the AppModule imports solved the issue.AppModule导入中删除BModule解决了这个问题。

I'll give you few suggestions.Remove all these as mentioned below我会给你一些建议。删除所有这些,如下所述

1)<script src="polyfills.bundle.js"></script>(index.html)  //<<<===not sure as Angular2.0 final version doesn't require this.

2)platform.bootstrapModule(App); (main.ts)

3)import { NgModule } from '@angular/core'; (app.ts)

使用 ngcWebpack 插件时,未指定 mainPath 或 entryModule 时出现此错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM