store selectSnapshot 데이터 get

agnusdei·2023년 7월 19일
0
this.auth = this.store.selectSnapshot(AuthState);

위의 코드 this.auth = this.store.selectSnapshot(AuthState);는 Angular 애플리케이션에서 @ngxs/store를 사용하여 앱 상태를 동기적으로 가져오는 방법을 보여주는 코드입니다.

@ngxs/store는 Angular 앱의 상태 관리를 쉽게 할 수 있도록 도와주는 라이브러리로서, 앱의 상태를 관리하고 상태 변화에 따라 UI를 업데이트할 수 있게 해줍니다.

this.store@ngxs/storeStore 클래스 인스턴스로서, 앱의 상태를 관리하는데 사용됩니다.

AuthState는 상태를 정의하는 클래스이며, @State() 데코레이터를 사용하여 선언되어야 합니다. AuthState가 어떻게 정의되었는지는 코드에서 확인할 수 없기 때문에 예시로 작성하겠습니다.

// 예시로 AuthState 상태를 정의한 클래스
import { State, Action, StateContext } from '@ngxs/store';
import { IAuthDTO } from '@aresa/interface';

export class AuthStateModel {
  authData: IAuthDTO | null;
}

@State<AuthStateModel>({
  name: 'auth',
  defaults: {
    authData: null,
  },
})
export class AuthState {
  // 액션 정의
  // @Action(...)
  // ...
}

AuthStateAuthStateModel의 상태를 관리하는 상태 클래스입니다. authDataIAuthDTO 형식의 인증 정보를 나타냅니다.

this.store.selectSnapshot(AuthState)는 현재 상태를 동기적으로 가져오는 메서드입니다. AuthState의 상태 데이터를 가져와서 this.auth 변수에 저장합니다.

일반적으로 selectSnapshot은 구독 없이 상태 값을 가져올 때 사용됩니다. 따라서 this.auth에는 AuthState의 현재 상태가 저장되어 있을 것입니다. 이후 코드에서 this.auth를 활용하여 앱의 상태를 참조하고 사용할 수 있습니다.

만약 상태가 변경될 때마다 업데이트를 감지하고 싶다면 select 메서드를 사용하여 구독할 수 있습니다. selectSnapshot을 사용하면 현재 상태만 가져오기 때문에 상태의 변화를 감지하지 않습니다. select 메서드를 사용하여 상태를 구독하면 상태가 변경될 때마다 새로운 값을 가져오게 됩니다.

// 예시로 구독하는 방법
import { Select } from '@ngxs/store';
// ...

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
})
export class ExampleComponent implements OnInit {
  @Select(AuthState) auth$!: Observable<IAuthDTO>;

  ngOnInit() {
    this.auth$.subscribe((authData) => {
      // 상태가 변경될 때마다 호출되는 콜백
      console.log(authData);
    });
  }
}

이렇게 구독을 사용하면 상태가 변경될 때마다 구독 함수가 호출되어 UI를 업데이트할 수 있습니다. selectSnapshot은 상태를 한 번만 가져오기 때문에 업데이트를 감지하는데에는 적합하지 않습니다. 구독을 통해 상태의 변화를 실시간으로 감지할 수 있습니다.

1개의 댓글

comment-user-thumbnail
2023년 7월 19일

정말 유익한 글이었습니다.

답글 달기