javascriptangulartypescriptdependency-injectionangular-dependency-injection

Restructuring a super call in a constructor to use the 'this'


I have the following service:

import {
  ENVIRONMENT_TOKEN
} from '@reg/environment/domain'

@Injectable({ providedIn: 'root' })
export class RegStore extends ImmutableStore<TRegState> {
  #env = inject(ENVIRONMENT_TOKEN)
  constructor() {
    super({
      name: 'RegistrationStore',
      mutationProducerFn: produce as unknown as MutationFn<TRegistrationState>,
      initialState: new RegState(),
      plugins: [
       // this.#env.signalStoryStorePlugins ERROR 'this' call cannot be used before 'super'
        useStorePersistence({
          persistenceKey: 'RegStore',
          persistenceStorage: localStorage,
          
        }),          
      ]
    })
  }

  store: Immutable<TRegState> = this.state()

}

How could the call - this.#env be restructured to remove the error?


Solution

  • You can call the inject inside the constructor so that it is a local variable to be sent to super, then save it to the class property.

    @Injectable({ providedIn: 'root' })
    export class RegistrationStore extends ImmutableStore<TRegistrationState> {
      #env: any;
    
      constructor() {
        const env = inject(ENVIRONMENT_TOKEN);
        super({
          name: 'RegistrationStore',
          mutationProducerFn: produce as unknown as MutationFn<TRegistrationState>,
          // enableLogging: !environment.production,
          initialState: new RegistrationState(),
          plugins: [
            env.signalStoryStorePlugins, 
            useStorePersistence({
              persistenceKey: 'RegStore',
              persistenceStorage: localStorage,
              
            }),          
          ]
        });
        this.#env = env;
      }
    
      store: Immutable<TRegState> = this.state()
    
    }