Angular 服务 - HTTP 请求更新信号

问题描述 投票:0回答:1

我有这样的服务:

const initialState: IUserState | null = null

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

private user = signal(initialState)

constructor (private http: HttpClient) {
  // setTimeout(() => this.user.set({ ...someFakeData }), 5000)
}

isAuthenticated = () => computed(() => !!this.user())

logIn = ({ email, password }: ILoginPayload) =>
  this.http.post<LoginResponse>(`some/url`, { email, password })
    .subscribe((data) => {
      this.user.set(data)
    })

}

export interface IUserState {
  platform_id: string
  name: string
  email: string
  picture_url: string
}

我还有一个登录组件,它调用 logIn 方法,如下所示:

  onSubmit = () =>
    this.authService.logIn({
      email: this.loginForm.value.email!,
      password: this.loginForm.value.password!
    })

当我尝试从

.subscribe
方法更新信号时,组件将不会接收到更改。 但是,当我在构造函数中取消注释超时并从那里更新信号时,组件会毫无问题地获取更改。因此,由于某种原因,我无法将数据传递给我的 http Observable 信号。

我做错了什么?或者有没有更好的模式来处理带有信号的http请求。 我尝试在网上寻找一些解决方案,但一无所获......

angular http signals
1个回答
0
投票

在 zonefull 应用程序中,更新信号本身不会触发更改检测。

调用

setTimeout
有效,因为它是
zone.js
修补的 API 之一。

可能的修复方法是调用

Promise.resolve()
安排变更检测周期。

© www.soinside.com 2019 - 2024. All rights reserved.