简体   繁体   English

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

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

I'm developing a demo authentication module as I'm still learning Angular.我正在开发一个演示身份验证模块,因为我仍在学习 Angular。 The auth page includes a form for authentication and once the user clicks "login" it triggers a post request and validate the message on the response to check if it's a success or error message.身份验证页面包含一个身份验证表单,一旦用户单击“登录”,它就会触发发布请求并验证响应中的消息以检查它是成功消息还是错误消息。 The problem is when I start the project using ng serve I get this error问题是当我使用 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'.

Here's the code in auth-req-service.ts file这是 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);
} );
}

I call this function after clicking the login button单击登录按钮后调用此函数

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

So why does it check the "response.message" at the beginning and not waiting for the click listener.那么为什么它在开始时检查“response.message”而不是等待点击侦听器。 it's pretty sure there's no response before clocking the button so there will be no message很确定在按下按钮之前没有响应所以不会有消息

That is because you use a generic post method without generic parameter.那是因为您使用了没有泛型参数的泛型post方法。 To fix this, you should do this:要解决此问题,您应该这样做:

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

This way the response won't be of type Object but of type any (or your concrete type if you use that type instead of any ).这样, response将不是Object类型,而是any类型(如果您使用该类型而不是any ,则为您的具体类型)。 For future reference, since you are using new HttpClientModule (the one since Angular 4.3 ) you should always use http methods ( POST , GET ,...) with generic parameters.为了将来参考,由于您使用的是新的HttpClientModule (自Angular 4.3以来的那个),您应该始终使用带有通用参数的 http 方法( POSTGET 、...)。

Here is the stackblitz example demonstrating this.是演示这一点的 stackblitz 示例。

Hope this helps.希望这可以帮助。

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

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