标头中。角度6

时间:2018-10-10 20:18:28

标签: angular rxjs angular-httpclient

我正在做一个示例,该示例是从同一网站上获取的,但是我不知道自己在做错什么,这会给我一个错误,即使我看着它,也看不到我在做什么。我做错了。

执行“ response => response.json()”时,出现以下错误:

  

json类型的Object属性不存在

我的服务如下:

import { Injectable } from '@angular/core';
import { HttpHeaders,HttpClient  } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class CompetenceService {

  public url: string;

  constructor(private httpCliente: HttpClient) {}

  public createUser(): Observable < any > {
    const getHeaders: HttpHeaders = new HttpHeaders({
      'Content-Type': 'application/json'
    });
    return this.httpCliente
      .get('http://xxx/xxx/xxx', {
        headers: getHeaders
      }).pipe(
        map(
          response => response.json() < --error: The 'json'
          property does not exist in the 'Object'
          type
        )
      );
  }
}

有人认为我做错了。

1 个答案:

答案 0 :(得分:1)

使用map时无需HttpClient。仅当您使用Http中的@angular/http时才需要

HttpClient为您提供实际的响应数据。因此,您不必像在使用json的情况下那样,就必须在响应中调用Http来获取实际数据。而且,如果这样做,由于响应数据上将没有名为json的方法,它将引发错误。这就是它所做的。

摆脱它,你应该就好了。

import { Injectable } from '@angular/core';
import { HttpHeaders, HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class CompetenceService {

  public url: string;

  constructor(private httpCliente: HttpClient) {}

  public createUser(): Observable < any > {
    const getHeaders: HttpHeaders = new HttpHeaders({
      'Content-Type': 'application/json'
    });
    return this.httpCliente
      .get('http://xxx/xxx/xxx', {
        headers: getHeaders
      });
  }
}