繁体   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