简体   繁体   中英

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.

The instructor is using angular 2, which has caused me problems elsewhere, but I was able to find updated solutions to them. 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:

 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. You dont need to use .json() to map result in 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. You can simply return the response from the API call.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM