Search code examples
typescriptngrxkali-linuxangular15

Unable access private variable outside the constructor


I am running my angular app in kali linux OS. the app was built successfully, but it throws error in loading. the error is shown below

main.ts:12 TypeError: Cannot read properties of undefined (reading 'select')
    at new UserService (user.service.ts:19:44)
    at Object.UserService_Factory [as factory] (user.service.ts:15:25)
    at R3Injector.hydrate (core.mjs:8121:35)
    at R3Injector.get (core.mjs:8009:33)
    at ChainedInjector.get (core.mjs:12179:36)
    at lookupTokenUsingModuleInjector (core.mjs:3255:39)
    at getOrCreateInjectable (core.mjs:3300:12)
    at Module.ɵɵdirectiveInject (core.mjs:10135:12)
    at NodeInjectorFactory.AppComponent_Factory [as factory] (app.component.ts:9:26)
    at getNodeInjectable (core.mjs:3485:44)

I am initializing a variable in service file which calls a store decleared in constructor of that service. it is undefined outside the constructor. preously this isn't thrown any error.

user.service.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Store } from '@ngrx/store';
import { Appstate } from '../state/app.state';
import { User as userState, Auth } from '../state/user/user.model';
import { Observable } from 'rxjs';
import { selectUser } from '../state/user/user.selectors';

@Injectable({
  providedIn: 'root',
})
export class UserService {
  user: Observable<userState> = this.store.select(selectUser);
  userName: string = '';

  constructor(private http: HttpClient, private store: Store<Appstate>) {
    this.user.subscribe({next: (res: any) => {
      this.userName = res.userEmail
    }})
  }

when I am keeping user inside constructor like below this is running as expected

constructor(private http: HttpClient, private store: Store<Appstate>) {
    store.select(selectUser).subscribe({next: (res: any) => {
      this.userName = res.userEmail
    }})
  }

one more thing, this problem arises when I upgraded to latest version of Angular and other packages. Previously I am using angular 14 and ngrx/store 13.1.0. Now I upgraged all packages to latest versions (Angular 15.1.5 and ngrx/store 15.2.1).

Can anyone tell me what I missing here? and why this occurs in latest version?


Solution

  • This is a recent change in TS. You can disable this behavior by setting the useDefineForClassFields option to false

    For more info see https://github.com/ngrx/platform/issues/3654