关于 Angular 13 中的 ModuleWithProviders 问题

huangapple go评论129阅读模式
英文:

Issue with ModuleWithProviders in Angular 13

问题

我已创建了一个模块,并在其 forRoot() 静态方法中添加了一个服务提供者。然后,我将该模块导入到 app.module.ts 中,并将其添加到 imports 部分:ZooModule.forRoot()。现在我正在尝试将 ZooModule 中的服务注入到 app.component.ts 构造函数中,但它显示:找不到名称 ZooService
请查看附加的截屏。如何使它工作?
提前感谢!

> ZooService
>
> ZooModule
>
> AppModule
>
> AppComponent

我尝试阅读 Angular 文档

英文:

I've created a module and added a service provider to its forRoot() static method. Then I've imported the module to app.module.ts and also added it to the imports section: ZooModule.forRoot(). Now I'm trying to inject the service from the ZooModule into app.component.ts constructor but it says: Can't find name ZooService.
Please, see the screenshots attached. How do I have it working?
Thanks for advance!

> ZooService
>
> ZooModule
>
> AppModule
>
> AppComponent

I tried to read the Angular documentation

答案1

得分: 0

第一件事: 你忘记在你的TypeScript文件中导入ZooService。

import { ZooService } from '../path/to/zoo.service.ts';

第二: 将会存在两个ZooService的实例。第一个来自于 {provideIn: 'root'},第二个来自于 ZooModule.providers。而第一个将无法访问动物。还有一种情况,第一个实例可能会被注入而无法访问动物,这会很难调试。我建议移除 {provideIn: 'root'} 以消除这种错误。

英文:

first thing: you forgot to import ZooService into your typescript file with AppComponent

import {ZooService} from '../path/to/zoo.service.ts

second: there will be two instances of ZooService. 1st comes from {provideIn: 'root'}. second from ZooModule.providers. and the 1st won't have access to animals. and there are cases where 1st instance would be injected with no access to animals which is pretty hard to debug. I would recomment removing {provideIn: 'root'} to get rid of such errors

huangapple
  • 本文由 发表于 2023年3月7日 19:54:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75661661.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定