繁体   English   中英

必须从注入上下文调用 inject()

[英]inject() must be called from an injection context

我正在尝试将我的 Angular 应用程序导出为 npm 模块以供其他应用程序使用,但遇到了一些困难。 我无法在互联网上的其他任何地方找到这个错误,我无能为力。

我遵循了本教程: https://medium.com/@nikolasleblanc/building-an-angular-4-component-library-with-the-angular-cli-and-ng-packagr-53b2ade0701e

我使用 ng-packagr 将我的应用程序导出为 npm 模块。 我可以从准系统测试应用程序的本地文件夹成功安装它,但无法让它显示我的应用程序。

错误:

    AppComponent.html:1 ERROR Error: inject() must be called from an injection context
    at inject (core.js:1362)
    at ChangeStackService_Factory (template-wiz.js:2074)
    at _callFactory (core.js:8223)
    at _createProviderInstance (core.js:8181)
    at resolveNgModuleDep (core.js:8156)
    at NgModuleRef_.push../node_modules/@angular/core/fesm5/core.js.NgModuleRef_.get (core.js:8849)
    at resolveDep (core.js:9214)
    at createClass (core.js:9094)
    at createDirectiveInstance (core.js:8971)
    at createViewNodes (core.js:10191)

template-wiz.module.ts(正在导出的模块)

    import { NgModule, ChangeDetectorRef, ComponentFactoryResolver } from '@angular/core';
    import { TemplateWizComponent } from './template-wiz.component';
    import { BrowserModule } from '@angular/platform-browser';
    import { FormsModule } from '@angular/forms';
    import { HttpClientModule } from '@angular/common/http';
    import { BlockListDirective } from './Directives/block-list.directive';
    import { TemplateItemsDirective } from './Directives/template-items.directive';
    import { ContextMenuComponent, SeperatorComponent, DragBoxComponent, SnapLineComponent, PropertiesComponent, ToolboxComponent } from './Components'
    import { AddressBlockComponent, TextBlockComponent, ImageBlockComponent, DataBlockComponent } from './Data-Blocks';
    import { BlockFactoryService, BlockRegistryService, DisplayInfoService, MouseClickService, SavingService, SnapService, TextHelperService, UserModeService } from './Services';
    import { PageContextMenuComponent } from './Components/page-context-menu/page-context-menu.component';
    import { CamelToWordsPipe } from './Pipes/camel-to-words.pipe';
    import { PdfPublisherService } from './Services/pdf-publisher/pdf-publisher.service';
    import { GradientBlockComponent } from './Data-Blocks/gradient-block/gradient-block.component';
    import { PropToTypePipe } from './Pipes/prop-to-type.pipe';
    import { ShapeBlockComponent } from './Data-Blocks/shape-block/shape-block.component';
    import { CommonModule } from '@angular/common';
    import { ModuleWithProviders } from '@angular/compiler/src/core';


    @NgModule({
      imports: [
        CommonModule,
        FormsModule,
        HttpClientModule
      ],
      entryComponents: [
        AddressBlockComponent,
        ContextMenuComponent,
        DragBoxComponent,
        GradientBlockComponent,
        ImageBlockComponent,
        PageContextMenuComponent,
        SeperatorComponent,
        ShapeBlockComponent,
        SnapLineComponent,
        TextBlockComponent
      ],
      declarations: [
        TemplateWizComponent,
        DataBlockComponent,
        AddressBlockComponent,
        SeperatorComponent,
        BlockListDirective,
        TemplateItemsDirective,
        ImageBlockComponent,
        TextBlockComponent, DragBoxComponent,
        SnapLineComponent,
        ToolboxComponent,
        PropertiesComponent,
        ContextMenuComponent,
        PageContextMenuComponent,
        GradientBlockComponent,
        CamelToWordsPipe,
        PropToTypePipe,
        ShapeBlockComponent
      ],
      providers: [
        BlockFactoryService,
        BlockRegistryService,
        DisplayInfoService,
        MouseClickService,
        SavingService,
        SnapService,
        TextHelperService,
        UserModeService,
        PdfPublisherService
      ],
      //bootstrap: [TemplateWizComponent],
      exports: [
        TemplateWizComponent
      ]
    })
    export class TemplateWizModule {
      static forRoot(): ModuleWithProviders {
        return {
          ngModule: TemplateWizModule,
          providers: [
            ComponentFactoryResolver
          ]
        }
      }
    }

app.module.ts(使用我的模块的裸机测试应用程序)

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { FormsModule } from '@angular/forms';
    import { HttpClientModule } from '@angular/common/http';
    import { AppComponent } from './app.component';
    import { TemplateWizModule } from 'template-wiz';

    @NgModule({
      declarations: [
        AppComponent,
      ],
      imports: [
        BrowserModule,
        FormsModule,
        TemplateWizModule.forRoot(),
        HttpClientModule
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }

任何帮助或指示将不胜感激,谢谢。

在使用库时使用 npm link 似乎是一个问题。

查看以下问题: https : //github.com/angular/angular/issues/25813

剧透:在 angular.json 中使用“projects.$name.architect.build.options.preserveSymlinks: true”

我有同样的错误。

我发现我是从@angular/core导入Inject而不是@angular/core/testing

希望有帮助!

这是为我解决的问题:

添加以下行tsconfig.app.jsoncompilerOptions

"paths": { "@angular/*": [ "../node_modules/@angular/*" ] }

来源: https : //github.com/angular/angular/issues/25813#issuecomment-500091900

我遇到了类似的问题。 在带有 npm 链接的 Angular 应用程序中使用 Angular 库。

如前所述:“解决方案:在客户端项目的 angular.json 文件中使用 projects.$name.architect.build.options.preserveSymlinks: true,而不是库。” 在使用“ng serve”服务应用程序时工作。

但是,当使用“ng test”对应用程序进行单元测试时,错误仍然存​​在。 在 angular.json 文件中添加 preserveSymLinks :

projects.$name.architect.test.options.preserveSymlinks: true

也解决了这个问题。

当我创建一个在其工厂中使用另一个InjectionToken 的可摇树InjectionTokeninject() must be called from an injection context错误消息inject() must be called from an injection context ,例如

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

import { dependeeToken } from './dependee.token';

export const dependingToken = new InjectionToken<string>('depending', {
  factory: () => inject(dependeeToken) + ' depending';
  providedIn: 'root',
});

相反,我为依赖的InjectionToken添加了一个提供者到NgModule

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

import { dependeeToken } from './dependee.token';
import { dependingToken } from './depending.token';

@NgModule({
  providers: [
    {
      deps: [dependeeToken],
      provide: dependingToken,
      useFactory: dependee => dependee + ' depending',
    }
  ],
})
export class DependingModule {}

package.json摘录

{
  "dependencies": {
    "@angular/compiler": "6.1.9",
    "@angular/core": "6.1.9"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "0.8.4",
    "@angular/cli": "6.2.4",
    "@angular/compiler-cli": "6.1.9",
    "typescript": "2.9.2"
  }
}

为我解决的是使用 Injectable 装饰器中的providedIn 属性,而不是在导致我出现此错误消息的服务提供者的应用程序模块中注册服务。

@Injectable({
  providedIn: 'root'
})
export class HeroService {}

同样的问题在这里

我的案例:当我使用 Mat Dialog 时

import { Component, OnInit, Inject } from '@angular/core';

 constructor(
    @Inject(MAT_DIALOG_DATA) public data: any,
    public matDialogRef: MatDialogRef<MatConfirmDialogComponent>) { }

注入和注入是不同的:

注入是一个函数,注入是接口

我希望这可以帮助找到相同场景的人。

同样的问题,但我的情况更愚蠢......

我让npm install something在错误的文件夹中npm install something

所以只需 rm 错误的“node_modules”并在好文件夹中安装 npm x)

使用ng build --prod命令构建 angular 9.0.0-next.0时出现此错误。 降级到版本~8.2.8使我的 angular 应用程序再次运行。

它在与ng serve开发中运行良好,因此它似乎与 Ivy 相关联。

如果 Karma 测试出现错误,只需删除 de node_modules文件夹并重新安装。

我在测试 Angular 应用程序时遇到了类似的问题。 该应用程序导入了一个使用 npm 从 @bit 安装的服务。 该服务依赖于 MatSnackBar,它似乎导致与 OP 相同的错误。

为了让测试运行,我在配置测试模块时实例化了服务。

在下面的示例中, AsyncUIFeedbackService是通过 npm 从 Bit 安装的。 useValue设置为useValue的新实例,并存根MatSnackBar效果很好。

await TestBed.configureTestingModule({
      declarations: [GeneralInfoComponent],
      providers: [
        FormBuilder,
        { provide : AsyncUIFeedbackService, 
          useValue: new AsyncUIFeedbackService({} as MatSnackBar)}, // <----Create the service
      ],
      imports: [AsyncUIFeedbackModule]
    }).compileComponents();

我发现我是从 @angular/core 导入 Inject 而不是 @angular/core/testing。

我的情况是因为这个代码在`test-setup.ts`中丢失了。 我只有前两行。
 
 
 
  
  import 'jest-extended'; import 'jest-preset-angular/setup-jest'; import { getTestBed } from '@angular/core/testing'; import { BrowserDynamicTestingModule, platformBrowserDynamicTesting, } from '@angular/platform-browser-dynamic/testing'; getTestBed().resetTestEnvironment(); getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting(), { teardown: { destroyAfterEach: false }, });
 
 

有点困难的是,即使添加了这段代码,我也遇到了一个不同的无益错误,因为它是一个 Angular 库包,它有自己的 package.json ,其中缺少依赖项 @angular/platform-browser-dynamic

以上有所帮助,但我再次删除了此代码。
真正有帮助的是https://stackoverflow.com/a/68718393/217408

一个可发布的包

  • 不能有dependencies ,只有peerDependencies
  • 不应运行npm install 该库不得包含node_modules目录。

几个月以来, dependenciesnode_modules运行良好,但突然开始失败,现在如果不修复以上几点,更旧的提交就不再工作了。

对于遇到此问题并使用Angular Universal和与 npm 链接链接的自定义 Angular 库的每个人:

提到的将 preserveSymlinks 添加到 angular.json projects.$name.architect.build.options.preserveSymlinks: true缺少两部分。

要使dev:ssrserve:ssr工作,您需要在此处添加它: projects.$name.architect.server.options.preserveSymlinks: true

正如另一条评论中提到的,如果您使用测试,请不要在这里忘记它: projects.$name.architect.test.options.preserveSymlinks: true

如果此处未列出其他用例/位置,请在下方评论。

2022 年更新

我在 Angular 库工作区中遇到了这个问题。 我的目录结构看起来像这样

project
│   package.json
│
└───projects
│   │
│   └─── myLibApp
│       │   file111.txt
│       │   file112.txt
│       │   ...
│   
└─────── myLibExampleApp

我想向我的主库添加一些依赖项,我在myLibApp文件夹中做了npm i导致了这个问题。 我必须删除 lib 中的node_modules并在根级别package.json以及lib内部提供依赖关系,但只在根目录中执行npm i

也结束了这里

暂无
暂无

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

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