我正在尝试按照本文扩展一个抽象类 - https://nartc.me/blog/inheritance-angular-inject/,但我陷入了
inject() must be called from an injection context
错误。谁能向我解释一下,就像我五岁一样,在哪里以及如何放置所有东西:(
@Directive()
export abstract class Event implements OnInit {
protected route = inject(ActivatedRoute);
protected eventService = inject(EventService);
readonly id$ = this.route.params.pipe(
map((routeParams) => Number(routeParams['id']))
);
ngOnInit(): void {}
}
@Component({ ... })
export class EventPageComponent extends Event {
constructor() {
super();
}
}
我完全不明白
MY_TOKEN
部分。在我的app.module
和/或event.module
中尝试过这个:
providers: [
{
provide: ActivatedRoute,
useFactory: () => inject(ActivatedRoute),
},
{
provide: EventService,
useFactory: () => inject(EventService),
}
]
像 Angular 建议的那样在构造函数本身中使用注入:
@Injectable({providedIn: 'root'})
export class Car {
radio: Radio|undefined;
// OK: field initializer
spareTyre = inject(Tyre);
constructor() {
// OK: constructor body
this.radio = inject(Radio);
}
}
同样使用inject()方法,你不需要使用super(),Angular可以处理它。