본문으로 건너뛰기

함수: createStoreContext()

function createStoreContext<TValue>(): object;

정의 위치: packages/angular-store/src/createStoreContext.ts:48

아톰과 스토어 묶음을 컴포넌트 하위 트리와 공유할 수 있는 타입이 지정된 Angular 의존성 주입 컨텍스트를 생성합니다.

반환된 provideStoreContext 함수는 컨텍스트 값을 생성하는 팩터리를 받습니다. 정적 값 대신 팩터리를 사용하면 각 컴포넌트 인스턴스와 각 SSR 요청이 자체 상태를 받으므로 요청 간 오염을 방지할 수 있습니다.

사용자는 주로 생성자나 필드 이니셜라이저 같은 주입 컨텍스트 안에서 injectStoreContext()를 호출해 컨텍스트의 아톰과 스토어를 가져온 다음, injectSelector, injectSelector, injectAtom 같은 기존 훅과 조합합니다.

타입 매개변수​

TValue​

TValue extends object

반환값​

object

injectStoreContext()​

injectStoreContext: () => TValue;

반환값​

TValue

provideStoreContext()​

provideStoreContext: (factory) => Provider;

매개변수​

factory​

() => TValue

반환값​

Provider

예시​

const { provideStoreContext, injectStoreContext } = createStoreContext<{
countAtom: Atom<number>
totalsStore: Store<{ count: number }>
}>()

// Parent component provides the context
@Component({
providers: [
provideStoreContext(() => ({
countAtom: createAtom(0),
totalsStore: new Store({ count: 0 }),
})),
],
template: `<child-cmp />`,
})
class ParentComponent {}

// Child component consumes the context
@Component({ template: `{{ count() }}` })
class ChildComponent {
private ctx = injectStoreContext()
count = injectSelector(this.ctx.countAtom)
}

예외​

injectStoreContext()를 상위 컴포넌트의 프로바이더에 일치하는 provideStoreContext()가 없는 상태에서 호출하면 예외가 발생합니다.