Angular 8: 属性 'message' 在类型 'Object' 上不存在

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

我正在开发一个演示身份验证模块,因为我还在学习 Angular。授权页面包含一个用于身份验证的表单,一旦用户单击 "login",它就会触发一个 post 请求并验证响应中的消息以检查它是成功消息还是错误消息。 问题是当我使用 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 类型(或者你的 concrete 类型,如果你使用该类型而不是 any)。为了将来参考,由于您正在使用新的 HttpClientModule(自 Angular 4.3 以来的那个),您应该始终使用 http 方法 (POST, GET,...) 使用通用参数。

Here 是演示这一点的 stackblitz 示例。

希望对您有所帮助。