There might be someone who knows why NGXS state cannot change inside of HttpClient POST request.
ctx.patchState()
Only works outside HTTP POST request.
@Action(SignIn)
signin(ctx: StateContext<AppStateModel>, { payload }: SignIn) {
// ctx.patchState({isLoggedIn:true}) this works!
return this.api$.signin(payload)
.pipe(
tap((user: User) => {
console.log(user);
ctx.patchState({ isLoggedIn: true })
})
)
.subscribe(
(user: User) => {
ctx.patchState({ isLoggedIn: true })
}
)
}
There might be someone who knows why NGXS state cannot change inside of HttpClient POST request.
ctx.patchState()
Only works outside HTTP POST request.
@Action(SignIn)
signin(ctx: StateContext<AppStateModel>, { payload }: SignIn) {
// ctx.patchState({isLoggedIn:true}) this works!
return this.api$.signin(payload)
.pipe(
tap((user: User) => {
console.log(user);
ctx.patchState({ isLoggedIn: true })
})
)
.subscribe(
(user: User) => {
ctx.patchState({ isLoggedIn: true })
}
)
}
console.log
statement from inside the tap
being printed?
– user184994
Commented
Aug 26, 2018 at 19:32
Actually, the state is changing, but you don't see it because you return subscription that hasn't been pleted. In other words - You'll see the action being dispatched once the subscription of the returned observable pletes.
As mentioned in the ments, the returned observable of the actions are being subscribed behind the scene, so there's no need to subscribe to it again.
After that being said, you can pass take(1)
in the pipe.
What it does, it pletes the subscription of the observable after it triggered once.
@Action(SignIn)
signin(ctx: StateContext<AppStateModel>, { payload }: SignIn) {
return this.api$.signin(payload)
.pipe(
take(1), // <-- Add that
tap((user: User) => ctx.patchState({ isLoggedIn: true }))
);
}