我面临一个奇怪的问题。
所以我的函数authenticateUser
返回并像这样数组
{
success: false,
msg: "invalid password"
}
但是当我尝试检查success == false
时是否出现错误
在对象类型上没有这样的属性
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']);
}
我尝试使用其他教程中的示例,但仍然没有解决办法
答案 0 :(得分:1)
您有2种方法可以做到这一点:
选项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']);
}
}
答案 1 :(得分:0)
对Angular不太熟悉,但这是因为数据键入不正确,您可以通过强制转换或类型保护来解决此问题。
const hasSuccess = (something: any): something is {success: boolean} {
return "success" in something;
}
if(hasSuccess(data) && data.success) ...