all-threads-bot

Frontender`s Spectre

Understanding Angular Injection Context

26 апреля 2023 г., 23:46
inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with `runInInjectionContext`. 
let _currentInjector = undefined;export function getCurrentInjector() {  return _currentInjector;}export function setCurrentInjector(injector: Injector|undefined|null {  const former = _currentInjector;  _currentInjector = injector;  return former;}
let _injectImplementationexport function getInjectImplementation() {  return _injectImplementation;}
export function assertInInjectionContext(debugFn: Function): void {  if (!getInjectImplementation() && !getCurrentInjector()) {    throw new RuntimeError(        RuntimeErrorCode.MISSING_INJECTION_CONTEXT,        ngDevMode &&            (debugFn.name +             '() can only be used within an injection context such as a constructor, a factory function, a field initializer, or a function used with `runInInjectionContext`'));  }}
import {  ElementRef,  assertInInjectionContext,  inject,} from '@angular/core';export function injectNativeElement<T extends Element>(): T {  assertInInjectionContext(injectNativeElement);  return inject(ElementRef).nativeElement;}
export const FOO = new InjectionToken('FOO', {  factory() {    const value = inject(SOME_PROVIDER);    return ...  },});
@Component({  providers: [    {      provide: FOO,      useFactory() {        const value = inject(SOME_PROVIDER);        return ...      },    },  ]})export class FooComponent {}
@Component({})export class FooComponent {  foo = inject(FOO);  constructor(private ngZone: NgZone = inject(NgZone)) {    const bar = inject(BAR);  }}
import { runInInjectionContext } from '@angular/core';export class FooComponent {  ngOnInit() {    runInInjectionContext(this.injector, () => {      console.log(        'I can access the NodeInjector using inject()',        inject(ElementRef)      );    })}