【发布时间】:2018-09-11 20:55:32
【问题描述】:
我正在通过 Angular 的 upgrade guide 学习如何在 Angular 应用程序中嵌入 AngularJS 组件。我使用 Angular CLI 创建了一个简单的 Angular 应用程序,并添加了一个简单的 AngularJS 模块作为依赖项。
当我运行ng serve 时,应用程序编译时没有错误。但是,在运行时,我在控制台中收到此消息:
Error: Trying to get the AngularJS injector before it being set.
是什么导致了这个错误,我该如何避免它?我没有偏离升级指南中详述的步骤。
这是我在 Angular 应用程序中升级 AngularJS 组件的方法:
// example.directive.ts
import { Directive, ElementRef, Injector } from '@angular/core';
import { UpgradeComponent } from '@angular/upgrade/static';
// this is the npm module that contains the AngularJS component
import { MyComponent } from '@my-company/module-test';
@Directive({
selector: 'my-upgraded-component'
})
export class ExampleDirective extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
// the .injectionName property is the component's selector
// string; "my-component" in this case.
super(MyComponent.injectionName, elementRef, injector);
}
}
这是我的app.module.ts:
// app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { UpgradeModule } from '@angular/upgrade/static';
import { ExampleDirective } from './example.directive';
import { myModuleName } from '@my-company/module-test';
@NgModule({
declarations: [AppComponent, ExampleDirective],
imports: [BrowserModule, AppRoutingModule, UpgradeModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {
constructor(private upgrade: UpgradeModule) {}
ngDoBootstrap() {
this.upgrade.bootstrap(document.body, [myModuleName], {
strictDi: true
});
}
}
我正在使用 Angular 5.2.0。
【问题讨论】:
-
为什么引用
@my-company/module-test时每个文件的import语句都不一样?您似乎也没有对第一个文件中导入的MyComponent执行任何操作。 -
@Pop-A-Stash - 我稍微简化了示例,但我更新了我的问题以说明我为什么导入组件;这样我就可以引用组件的选择器字符串,该字符串存储为组件类的属性。这两个文件从
@my-company/module-test导入不同的东西,因为模块导出了多个命名导出。 -
我在 Angular 的 GitHub 上打开了一个问题:github.com/angular/angular/issues/23141
-
当我在多个 NgModule 中导入
UpgradeModule时出现此错误。一旦我删除它,它就消失了。
标签: javascript angularjs angular typescript angular-upgrade