使用 angular 的 HttpClient 模块从 mysql 获取数据时出错 5
Error while getting data from mysql using HttpClient module of angular 5
我创建了一个从中获取数据的服务,但我遇到了以下错误:
ERROR TypeError: this.http.get(...).map is not a function
我正在使用 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
,您需要导入 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
。
我创建了一个从中获取数据的服务,但我遇到了以下错误:
ERROR TypeError: this.http.get(...).map is not a function
我正在使用 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
,您需要导入 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
。