簡體   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