ngxs-labs / select-snapshot

🌊 Flexibile decorator that allows to get a snapshot of the state
MIT License
42 stars 4 forks source link

Uncaught ReferenceError: Cannot access 'State' before initialization #151

Closed bot101 closed 2 years ago

bot101 commented 2 years ago

I'm submitting a...


[ ] Regression (a behaviour that used to work and stopped working in a new release)
[x] Bug report  
[ ] Performance issue
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => https://github.com/ngxs/store/blob/master/CONTRIBUTING.md
[ ] Other... Please describe:

Current behaviour

I get this error Uncaught ReferenceError: Cannot access 'AuthState' before initialization when I use @SelectSnapshot in a service but it works fine in a component or an interceptor. Replacing @SelectSnapshot with store.selectSnapshot works fine.

Does anyone know why this is happening?

Expected behavior

Do not throw a reference error and work as expected in a service

Minimal reproduction of the problem with instructions

Sample code that triggers the error:

import { Injectable } from '@angular/core';
import { EmitterService } from '@ngxs-labs/emitter';
import { SelectSnapshot } from '@ngxs-labs/select-snapshot';
import { Store } from '@ngxs/store';
import { ApiService } from 'src/app/services/api/api.service';
import { AuthState } from '../../state/auth.state';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  @SelectSnapshot(AuthState.token) token: string | null; // <- Uncaught ReferenceError: Cannot access 'AuthState' before initialization

  constructor(private readonly apiService: ApiService, private emitter: EmitterService) { }

  logout() {
    const token = ''; // this.store.selectSnapshot(AuthState.token); // Works!
    const subscription = this.apiService.post<any>('user/logout', {token});
    subscription.subscribe(() => {
      this.emitter.action(AuthState.logout).emit();
      //TODO: Handle elsewhere (at state level maybe)
      // this.router.navigate(['/login']);
    });
    return subscription;
  }
}

Libs:
- @angular/core version: 13.2.6
- @ngxs/store version: 3.7.3


Browser:
- [x] Chrome (desktop) version XX
- [ ] Chrome (Android) version XX
- [ ] Chrome (iOS) version XX
- [ ] Firefox version XX
- [ ] Safari (desktop) version XX
- [ ] Safari (iOS) version XX
- [ ] IE version XX
- [ ] Edge version XX

For Tooling issues:
- Node version: v16.15.0
- Platform: Windows

Others:

bot101 commented 2 years ago

Just figured out the issue! This is happening due to a cyclic dependency between AuthState and AuthService that I should have seen the first time. Closing now.