Angular 14 中更简洁的抽象构造函数

问题描述 投票:0回答:1

我正在尝试按照本文扩展一个抽象类 - 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 inheritance dependency-injection
1个回答
0
投票

像 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可以处理它。

整个文档的链接:https://angular.io/api/core/inject

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.