简体   繁体   English

Angular 无提供者的服务注入错误

[英]Angular service injection error for no provider

I have an angular app (v10.1) that is using routing.我有一个使用路由的 angular 应用程序(v10.1)。

In short, I am using modules to take advantage of lazy loading the basic dir structure looks like this简而言之,我正在使用模块来利用延迟加载,基本的 dir 结构看起来像这样

ROOT
    /modules
        /myMod
            myMod.component.ts

the myMod component needs to make use of some services, and so I am trying to include the service (location.service) and declare it in the constructor. myMod 组件需要使用一些服务,所以我试图包含服务(location.service)并在构造函数中声明它。

I get an error我收到一个错误

core.js:4352 ERROR Error: Uncaught (in promise): 
    NullInjectorError: R3InjectorError(myModModule)[LocationService -> LocationService -> LocationService -> LocationService -> LocationService]: 
    NullInjectorError: No provider for LocationService!

I have tried to add this service to a provider array in @NgModule BUT I have 3 modules to consider ROOT,Resource,myMod我试图将此服务添加到@NgModule 中的提供程序数组中,但我有 3 个模块需要考虑 ROOT、Resource、myMod

I have tried adding the service to each of these respectively, to no avail - still get the error我已尝试将服务分别添加到其中的每一个,但无济于事 - 仍然出现错误

Here is a little bit more detailed diagram of the app Please dont tell me I need to add the service to each of the mods, and if Im missusing modules can someone please explain.这是应用程序的更详细的图表请不要告诉我我需要将服务添加到每个模块中,如果我错过了模块,请有人解释。 Thx谢谢

ROOT
-app.module
-app-routing.module
-app.component.html (has link routerLink="/resources/myMod" )

-- modules/resources
----resources-routing.module.ts
        const routes: Routes = [{
                path: 'myMod', loadChildren: () => import('../myMod/myMod.module').then((m) => m.myModModule),
            }]

-- modules/myMod
----myMod.module.ts
        import { myModRoutingModule } from './myMod-routing.module';
        import { myModComponent } from './myMod.component';
        @NgModule({
            declarations: [myModComponent],
            imports: [CommonModule, myModRoutingModule]
        })
        export class myModModule {}

----myMod.component.ts
        import { LocationService } from '../../common/services/location.service';
        @Component({
            selector: 'app-myMod',
            templateUrl: './myMod.component.html'
        })
        export class myModComponent implements OnInit {
            constructor( private locationService: LocationService )

https://stackblitz.com/edit/angular-injection-error1 https://stackblitz.com/edit/angular-injection-error1

在此处输入图像描述

It looks like your @Injectable annotation is missing the providedIn property.看起来您的@Injectable注释缺少providedIn属性。

Adding it should resolve the issue:添加它应该可以解决问题:

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

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

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