【问题标题】:How can my injected service (LoggingService) is working without @Injectable being used?我的注入服务 (LoggingService) 如何在不使用 @Injectable 的情况下工作?
【发布时间】:2019-07-15 02:31:20
【问题描述】:

我试图将服务(LoggingService)注入另一个服务(AccountService),所以accountsService 肯定需要@Injectable 来探测地注入它.....问题是我只是将它添加到构造函数而不添加@Injectable,它是正常工作.......如何在不使用@Injectable 的情况下运行我的应用程序?

import { LoggingService } from "./logging.service";

export class AccountsService {
    constructor(private loggingService: LoggingService) {}

    accounts = [{
            name: 'Master Account',
            status: 'active'
        },
        {
            name: 'Testaccount',
            status: 'inactive'
        },
        {
            name: 'Hidden Account',
            status: 'unknown'
        }
    ];

    addAccount(newAccount: {name: string, status: string}) {
        this.accounts.push(newAccount);
        this.loggingService.loggingStatusChange(newAccount.status);
    }

    updateStatus(id: number, status: string) {
        this.accounts[id].status = status;
        this.loggingService.loggingStatusChange(status);
    }
}

【问题讨论】:

  • 不应该。您是否有示例 StackBlitz 可以复制此问题?

标签: javascript angular


【解决方案1】:

只要您不注入或使用 AccountsService 应用可见的任何组件,它就可以正常工作(我所说的可见是指在@NgModule() 类装饰器中是否“导入/声明/提供”。

如果您已经在某处使用了 AccountsService,并且您的应用没有对您大喊 error。然后它可能在您的应用程序某处的@NgModule({}) 中提供。否则就没有办法了。

【讨论】:

    猜你喜欢
    • 2021-11-18
    • 2018-05-11
    • 2021-03-12
    • 1970-01-01
    • 2013-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多