我正在尝试从组件内的延迟加载模块访问服务实例。该模块没有任何可用于基于构造函数的注入的组件。Angular 文档没有帮助,我在 Medium 和类似网站上找到的所有各种教程都不适用。
以下是执行服务延迟加载的组件的代码。
await import ('./lazy.module')
.then(module => module.LazyModule)
.then(module => {return module;})
.then(module => this.compiler.compileModuleAsync(module))
.then(factory => {
let module = factory.create(this.injector);
this.lazyService = module.injector.get(LazyService);
});
Run Code Online (Sandbox Code Playgroud)
问题在于,在当前组件中包含 LazyService 将无法达到延迟加载的目的,并且 get() 方法似乎需要一个类型,这种方法只会产生先有鸡还是先有蛋的问题。我将 InjectionToken 作为另一种选择,但它需要一个通用定义,再次需要导入 LazyService。
谁能解释一下延迟服务加载应该如何完成?
错误信息:
错误 NullInjectorError:R3InjectorError(AppModule)[AlertPanelComponent -> AlertPanelComponent -> AlertPanelComponent]:NullInjectorError:没有 AlertPanelComponent 的提供程序!角
我不明白这一点,我只是想AlertPanelComponent从alert-panel.component 导入我的。
在 stackOverflow 上搜索时,这个错误似乎非常广泛。我已将其放入我的 app.module 中。
应用程序组件.ts
import {AlertClass} from './models/alert-class.model';
...
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, DoCheck {
...
constructor( private restService:RestService,
private sanitizer: DomSanitizer,
private router:Router,
private alertPanelComponent:AlertPanelComponent ){
}
...
}
Run Code Online (Sandbox Code Playgroud)
应用程序模块.ts
import { AlertPanelComponent } from './alert-panel/alert-panel.component';
...
@NgModule({
declarations: [
AlertPanelComponent,
...
],
...
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)
应用程序路由.module.ts
import { NgModule } …Run Code Online (Sandbox Code Playgroud) 我正在尝试将服务注入管道中。通常,inject(...)工作正常,但在管道上下文中我收到错误:
Error: NG0203: inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with `EnvironmentInjector#runInContext`
Run Code Online (Sandbox Code Playgroud)
我做错了什么或者我怎样才能让它工作?
当我将依赖项放入构造函数中时,该服务工作正常,例如constructor(private service: CheckboxFilterPipe),但我现在想在组件代码中使用它(transform()以编程方式使用),不再可以选择在构造函数中编写依赖项。
@Pipe({
name: 'checkboxFilter',
pure: true,
})
export class CheckboxFilterPipe implements PipeTransform {
/** */
private service = inject(CheckboxFilterService);
constructor() {}
transform(items: Array<any>, filter: IFilterSettings, defaultFilter?: IFilterDefaults): any {
this.service.init();
return this.service.doFilter(items, filter, defaultFilter);
}
}
Run Code Online (Sandbox Code Playgroud)
感谢您的帮助!