簡體   English   中英

Angular 7 - '屬性 json 不存在於類型 Object'

[英]Angular 7 - 'Property json does not exist on type Object'

我正在學習有關構建 MEAN 堆棧身份驗證應用程序的教程,但我的 auth.server.ts 文件中的 registerUser 函數出現問題。

講師正在使用 angular 2,這在其他地方給我帶來了問題,但我能夠找到更新的解決方案。 這個錯誤導致我在其他一些課程中出現問題,我不知道如何解決它。

這是我的代碼:

 registerUser(user) { let headers = new HttpHeaders(); headers.append('Content-Type', 'application/json'); return this.http.post('http://localhost:5000/users/register', user, { headers: headers }).pipe(map(res => res.json())); }

如果需要,這里是完整的 auth.service.ts 文件:

 import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { map } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class AuthService { authToken: any; user: any; constructor(private http: HttpClient) { } registerUser(user) { let headers = new HttpHeaders(); headers.append('Content-Type', 'application/json'); return this.http.post('http://localhost:5000/users/register', user, { headers: headers }).pipe(map(res => res.json())); } }

對於 Angular 7,建議使用 HttpClient 而不是 Http。 您不需要使用 .json() 在 HttpClient 中映射結果。 您可以在下面找到用於此的示例代碼:

import { HttpClient } from '@angular/common/http';

registerUser(user) {
  let headers = new HttpHeaders();
  headers.append('Content-Type', 'application/json');
  return this.http.post('http://localhost:5000/users/register', user, { headers: headers });
}

如果您使用的是HttpClient而不是Http那么您不需要使用管道或需要將其映射到 json。 您可以簡單地從 API 調用返回響應。

  registerUser(user) {
    let headers = new HttpHeaders();
    headers.append('Content-Type', 'application/json');
    return this.http.post('http://localhost:5000/users/register', user, { headers: headers });
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM