首页 > 解决方案 > 类型上不存在属性

问题描述

我面临一个奇怪的问题。所以我的函数authenticateUser像这样返回和数组

{
  success: false,
  msg: "invalid password"
}

但是当我试图检查success == false我是否收到错误类型 Objects 上没有此类属性时

 this.authService.authenticateUser(user).subscribe(data=>{
  if(data.success){//here need to check response for success
    console.log(data)
    this.authService.storeUserData(data);
    this.router.navigate(['/user']);
  }else{
    this.router.navigate(['/login']);
  }

我尝试使用其他教程中的示例,但仍然没有解决方案

标签: angulartypescript

解决方案


您有两种方法可以做到这一点:

选项 1 使用类型any

this.authService.authenticateUser(user).subscribe((data: any)=>{
  if(data.success){//here need to check response for success
    console.log(data)
    this.authService.storeUserData(data);
    this.router.navigate(['/user']);
  }else{
    this.router.navigate(['/login']);
  }
}

或者做强类型{success: boolean, msg: string}或创建这种类型的接口:

this.authService.authenticateUser(user).subscribe((data: {success: boolean, msg: string}) =>{
  if(data.success){//here need to check response for success
    console.log(data)
    this.authService.storeUserData(data);
    this.router.navigate(['/user']);
  }else{
    this.router.navigate(['/login']);
  }
}

推荐阅读