繁体   English   中英

Angular 8:“对象”类型上不存在“消息”属性

[英]Angular 8: Property 'message' does not exist on type 'Object'

我正在开发一个演示身份验证模块,因为我仍在学习 Angular。 身份验证页面包含一个身份验证表单,一旦用户单击“登录”,它就会触发发布请求并验证响应中的消息以检查它是成功消息还是错误消息。 问题是当我使用 ng serve 启动项目时出现此错误

 ERROR in src/app/auth-req.service.ts(26,38): error TS2339: Property 'message' does not exist on type 'Object'.
src/app/auth-req.service.ts(27,20): error TS2339: Property 'message' does not exist on type 'Object'.

这是 auth-req-service.ts 文件中的代码

constructor(private authS: AuthReqService, private generalS: GeneralSService, private route: Router) {}

login(userData: {email: string, password: string}) {
  this.http.post('http://localhost/apiapp/login.php', userData).pipe(catchError(
  (errorRes) => {
  console.log(errorRes.url);
  console.log(errorRes.name);
  console.log(errorRes.message);
  return throwError(errorRes);
}
)).subscribe( (response) => {
  this.responseMsg.next(response.message);
  if (response.message === 'Logged in') {
    localStorage.setItem('isLoggedIn', '1');
    this.generalS.isAuthenticated.next(true);
  } else {
    this.generalS.isAuthenticated.next(false);
  }
}, error => {
  // alert(error.message);
} );
}

单击登录按钮后调用此函数

submitForm(form: NgForm) {
  let email: string = form.value.email;
  let  password: string = form.value.password;
  let userData = {email, password};
  this.authS.login(userData);

那么为什么它在开始时检查“response.message”而不是等待点击侦听器。 很确定在按下按钮之前没有响应所以不会有消息

那是因为您使用了没有泛型参数的泛型post方法。 要解决此问题,您应该这样做:

this.http.post<any>(....)   // instead of "any" you can use concrete type of "response" that you expect

这样, response将不是Object类型,而是any类型(如果您使用该类型而不是any ,则为您的具体类型)。 为了将来参考,由于您使用的是新的HttpClientModule (自Angular 4.3以来的那个),您应该始终使用带有通用参数的 http 方法( POSTGET 、...)。

是演示这一点的 stackblitz 示例。

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM