简体   繁体   English

Angular 7 - '属性 json 不存在于类型 Object'

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

I am following a tutorial on building a MEAN stack authentication app, and I have a problem with my registerUser function that's in my auth.server.ts file.我正在学习有关构建 MEAN 堆栈身份验证应用程序的教程,但我的 auth.server.ts 文件中的 registerUser 函数出现问题。

The instructor is using angular 2, which has caused me problems elsewhere, but I was able to find updated solutions to them.讲师正在使用 angular 2,这在其他地方给我带来了问题,但我能够找到更新的解决方案。 This error has caused me problems with a few other courses and I'm not sure how to fix it.这个错误导致我在其他一些课程中出现问题,我不知道如何解决它。

Here is my code:这是我的代码:

 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())); }

Here is the complete auth.service.ts file if you need it:如果需要,这里是完整的 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())); } }

For Angular 7, it is adviced to use HttpClient rather then Http.对于 Angular 7,建议使用 HttpClient 而不是 Http。 You dont need to use .json() to map result in HttpClient.您不需要使用 .json() 在 HttpClient 中映射结果。 Below you can find example code for this:您可以在下面找到用于此的示例代码:

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 });
}

If you are using HttpClient not the Http then you don't need to use pipe or need to map it to json.如果您使用的是HttpClient而不是Http那么您不需要使用管道或需要将其映射到 json。 You can simply return the response from the API call.您可以简单地从 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