我找到了几篇关于该主题的帖子,但我显然遗漏了一些东西。
我的主要目标是使用需要参数的 Injectable。
我发现正确的方法是使用装饰器@Inject。
您可以在这里看到我的尝试:https://stackblitz.com/edit/stackblitz-starters-r5psb2?devToolsHeight=33&file=src%2Ftest-component.component.ts
如果您无法加载该页面:
文件 test-service.service.ts
import { Inject, Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class TestService {
constructor(@Inject('arg1') public arg1: string) {}
}
文件 test-component.component.ts
import { Component } from '@angular/core';
import { TestService } from './test-service.service';
@Component({
selector: 'app-test-component',
standalone: true,
imports: [],
template: `<span>{{testService.arg1}}</span>`,
providers: [
{
provide: 'arg1',
useValue: 'value1',
},
],
})
export class TestComponent {
constructor(public testService: TestService) {}
}
输出
ERROR
Error: R3InjectorError(Environment Injector)[TestService -> arg1 -> arg1]:
NullInjectorError: No provider for arg1!
你的服务是
providedIn:'root'
,所以这意味着它是在根注入器中定义的。
通过做
{
provide: 'arg1',
useValue: 'value1',
},
您只需在
NodeInjector
中定义值,即只属于该组件的注入器。
要修复它,您应该在应用程序的根目录下声明。
bootstrapApplication(AppComponent, {providers: [{ provide: 'arg1', useValue: 'value1']}