如何在Angular中触发编译时错误?解决服务未注册无编译报错问题
Angular依赖注入编译时未检测服务未注册的问题
我需要创建一个依赖CounterService的StepperComponent,但现在的问题是——如果忘记在providers中注册CounterService,编译器不会抛出任何错误。这导致代码迁移时无法完全放心,编译明明没报错,但用户访问页面时组件会直接显示为空。
使用示例
projects/showcase/src/app/app.component.ts
import { Component } from '@angular/core'; import { CommonModule } from '@angular/common'; // import { UiSdkComponent } from '@mycomp/ui-sdk'; import { ButtonModule } from '@mycomp/ui-sdk/button'; import { TranslatePipe } from '@mycomp/ui-sdk/i18n'; import { StepperModule } from '@mycomp/ui-sdk/stepper'; import { CounterService } from '@mycomp/ui-sdk/counter'; @Component({ selector: 'app-root', standalone: true, imports: [ CommonModule, // UiSdkComponent, ButtonModule, TranslatePipe, StepperModule, ], providers: [ CounterService ], templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent { title = 'showcase'; }
Stepper组件与CounterService(均属于@mycomp/ui-sdk库)
projects/mycomp/ui-sdk/stepper/src/stepper.module.ts
@NgModule({ declarations: [ StepperComponent, ], imports: [ CommonModule, ButtonModule ], exports: [ StepperComponent, ], }) export class StepperModule {}
projects/mycomp/ui-sdk/stepper/src/stepper.component.ts
import { Component } from '@angular/core'; import { CounterService } from '@mycomp/ui-sdk/counter'; @Component({ selector: 'lib-stepper', templateUrl: './stepper.component.html', styleUrls: ['./stepper.component.css'], }) export class StepperComponent { constructor(public counterService: CounterService) {} }
projects/mycomp/ui-sdk/counter/src/counter.service.ts
import { Injectable } from '@angular/core'; @Injectable() export class CounterService { count: number; constructor() { this.count = 0; } increment() { this.count += 1; } decrement() { this.count -= 1; } }
内容的提问来源于stack exchange,提问作者Jason Rich Darmawan
相关产品推荐
相关产品推荐

