Call inject() inside a property decorator

Discussão em 'Angular' iniciado por Sherif eldeeb, Setembro 10, 2024.

  1. I want to create a decorator that injects and uses a service

    function MyDecorator(){
    return function(target: any, prop: string){
    // error: inject() must be called from an injection context
    let service = inject(MyService);

    // trying to call it inside the constructor
    // but it seems that the constructor already called
    let constructor = target.constructor;
    target.constructor = function(...args: any[]){
    constructor.apply(this, args);
    service = inject(MyService)
    }

    // trying to call it inside ngOnInit
    // will fail according to the docs because it is too late
    // https://angular.dev/errors/NG0203

    }
    }


    using runInInjectionContext() also impossible because it needs something to be injected

    return function(target: any, prop: string){
    // inject environmentInjector somehow

    runInInjectionContext(this.environmentInjector, () => {
    service = inject(MyService);
    });

    }


    Usage:

    @Component(...)
    class MyComp{
    @Mydecorator() myProp: string
    }


    I don't want the consumer of this decorator to make any special changes to his component.

    update:

    solved initially by using AppInjector

    export let AppInjector: Injector;

    @Component(...)
    export class AppComponent{
    constructor(private injector: Injector) {
    AppInjector = this.injector;
    }
    }


    though it still gives an error ASSERTION ERROR: Unexpected state: hydrating an <ng-container>, but no hydration info is available. [Expected=> number === object <=Actual], but till now I can inject the service.

    Continue reading...

Compartilhe esta Página