【问题标题】:Angular 8: Property 'message' does not exist on type 'Object'Angular 8:“对象”类型上不存在属性“消息”
【发布时间】:2020-02-09 09:53:44
【问题描述】:

我正在开发一个演示身份验证模块,因为我还在学习 Angular。 auth 页面包含一个用于身份验证的表单,一旦用户单击“登录”,它就会触发发布请求并验证响应中的消息,以检查它是成功消息还是错误消息。 问题是当我使用 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”而不是等待点击侦听器。很确定在按下按钮之前没有响应,所以不会有消息

【问题讨论】:

    标签: angular authentication http-post


    【解决方案1】:

    那是因为您使用了没有泛型参数的泛型 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 ,...) 带有泛型参数。

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

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2020-10-31
      • 2022-07-23
      • 2021-04-02
      • 2019-12-24
      • 2018-11-04
      • 1970-01-01
      • 1970-01-01
      • 2019-05-18
      • 2017-12-02
      相关资源
      最近更新 更多