简体   繁体   中英

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

I'm developing a demo authentication module as I'm still learning 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

 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

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. 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. 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 ). 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.

Here is the stackblitz example demonstrating this.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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