【问题标题】:how to set the scope to a module?如何将范围设置为模块?
【发布时间】:2021-08-30 12:52:48
【问题描述】:

角度 12

假设我有一个具有这种结构的项目:

/todo/components/...
/todo/services/todos.service.ts
/todo/todos.module.ts
app.module.ts
app.component.ts

我希望 todo.service.ts 服务仅移植到 /todo

/todo/services/todos.service.ts

@Injectable({ providedIn: TodoModule })
export class TodosService {

/todo/todo.module.ts

  providers: [TodosService],

我收到此错误: 未捕获的引用错误:在初始化之前无法访问词法声明“TodosStoreService”

我通过删除服务中的注入尝试了其他解决方案:

/todo/todos.module.ts

export class TodosService {

我没有错误,但在 app.component 中,注入是在服务上完成的,而我希望它仅在 todo 模块中可用

https://stackblitz.com/edit/angular-ivy-uf7zpe-module-service

【问题讨论】:

    标签: angular module


    【解决方案1】:

    TLDL:
    您应该在服务中导入您的模块 import { TodosModule } from '../todos.module'

    完成:
    按照文档:https://angular.io/guide/providers

    也可以指定一个服务应该在一个 特别是@NgModule。例如,如果您不希望 UserService 成为 可用于应用程序,除非它们导入您已安装的 UserModule 创建后,您可以指定应在 模块:

    import { Injectable } from '@angular/core';
    import { UserModule } from './user.module';
    
    @Injectable({
      providedIn: UserModule,
    })
    export class UserService {
    }
    

    上面的示例显示了在 模块。这种方法是首选的,因为它可以使 如果没有注入服务。如果无法指定 模块应该提供的服务,你也可以声明一个 模块内服务的提供者:

    import { NgModule } from '@angular/core';
    import { UserService } from './user.service';
    
    @NgModule({
      providers: [UserService],
    })
    export class UserModule {
    }
    

    【讨论】:

    • 这就是我所做的,我收到了这个错误消息:未捕获的 ReferenceError: can't access lexical declaration 'TodosStoreService' before initialization
    • 所以,试着把它放在 stackblitz 上。
    • 所以我希望将服务:TodoService 移植到模块:TodoModule
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-23
    • 1970-01-01
    • 2014-01-26
    相关资源
    最近更新 更多