首页 > 解决方案 > Angular 7 - '对象类型上不存在属性 json'

问题描述

我正在关注有关构建 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()));
  }
}

标签: angularmean-stack

解决方案


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

推荐阅读