【问题标题】:Error while getting data from mysql using HttpClient module of angular 5使用 Angular 5 的 HttpClient 模块从 mysql 获取数据时出错
【发布时间】:2018-01-16 17:26:46
【问题描述】:

我创建了一个从中获取数据的服务,但遇到以下错误:

ERROR TypeError: this.http.get(...).map 不是函数

我正在使用HttpClient 模块。这是我的脚本:

import {Injectable} from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class Api{
    public data: any = [];
    constructor(private http: HttpClient){ }

    getPartnersName(){
        return this.http.get('http://aff.local/getPartners.php', {
      observe: 'response',
      responseType: 'json'
    }).map(
        (data)=>{
          console.log(data)
        },
        error=>{
          console.log(error);
        }
      );
    }
}

编辑

我仍然看不到组件中的数据:

ngOnInit(){
    this.api.getPartnersName().subscribe(
        (data)=>{
          this.data = data;
        }
      );
  }

【问题讨论】:

  • HttpClient 中的默认响应类型是json 如果要控制台,则不需要使用map。使用do
  • HttpClient 实现已经包括map 的内部使用......它会自动为您工作。参考这个链接github.com/angular/angular/issues/20460

标签: angular httpclient angular5


【解决方案1】:

现在我知道问题所在了。使用HttpClient,您需要导入map 函数并将其与pipe 一起使用。同时删除responseType - 默认设置为json

import { map } from 'rxjs/operators/map'

在方法中

return this.http.get('http://aff.local/getPartners.php', {
          observe: 'response'
       }).pipe(
               map(data => { 
                      console.log(data);
                      return data;
               })
       );

仅用于记录。您可以使用do 函数而不是map

【讨论】:

  • 正确的是我仍然无法在我的 html 页面上看到数据
  • 但是你在你的函数中得到数据了吗?
  • 在我的问题末尾查看我的编辑。解决这个问题,我会投票并选择你的答案
  • @droidnation )))。显示组件模板
  • 这很明显。我们还没有退货。更新
猜你喜欢
  • 1970-01-01
  • 2020-07-20
  • 2014-07-29
  • 1970-01-01
  • 2018-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多