网站搜索

javascript - 使用异步方法将数据从服务传递到 Angular 组件


我正在我的服务中编写一个登录方法,当用户登录应用时,该方法会将数据传递给组件。这个登录方法会发送一个HTTP请求,如果成功,它会调用setAuthentication方法来更新我想要共享的属性。

但是当我想在组件中使用这些属性时,例如在一个显示用户名的仪表板页面上,使用

  public currentUser = this.authService.currentUser

我没有获取到更新的属性值,只是空值。

这是我的服务代码:

  public currentUserAuth:User | null =  null
  public currentUser:User | null =  null
  public currentState:authStatus = authStatus.Cheking
  

  public loginUser(loginInterface: loginInterface){
    const url = `${this.basicURL}/login`
    const body = {email: loginInterface.email, password1: loginInterface.password1}
    return this.http.post<loginResponse>(url, body)
    .pipe
    (map(({user, token, currentUser}) => this.setAuthentication(user, token, currentUser!)),
    catchError(err => throwError(() => err.error.message))
    )
  }

  public setAuthentication(userPayload:User, token:string, currentUser: User){
    this.currentUserAuth = userPayload
    this.currentState = authStatus.Authenticated
    this.currentUser = currentUser
    localStorage.setItem('token', token)
    
    return true
  }

我感谢任何帮助

答案#1

请将 currentUser 改为 getter 方法

public get currentUser(): any {
    return this.authService.currentUser;
}

如果你不喜欢使用 getter 方法,那么你需要在服务中设置值之后才设置 currentUser 属性,下面我假设服务中的 currentUser 在 ngoninit 运行之前已经被设置好了!

public currentUser;

ngOnInit(): void {
    this.currentUser = this.authService.currentUser;
}