我正在设置一个Angular应用程序。我的数据来自elastic.php文件。 每次执行搜索功能时,都会出现此错误。
this.http.Search(...).then is not a function
我在考虑问题是关于可观察的问题。也许它必须是toPromise()函数。 但是我不确定这一点,也不确定如何正确处理。
http.service.ts
Search(body: any): any {
const proxyBody = {
path: 'doctyp136,doctyp135,doctyp134/_search',
body: body
};
return this.http.post( environment.elastic_url, proxyBody, {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})} ).subscribe((result) => {
console.log(result);
});
}
elastic.php
<?php
/**
* Elastic php proxy
*/
const ELASTIC_BASE_URL = "http://localhost:9210/fud_fret_web/";
/*
* 1) Gather infos from
*/
// Takes raw data from the request
$json = file_get_contents('php://input');
// Converts it into a PHP object
$data = json_decode($json);
$elasticSubPath = $data['path'];
$elasticBody = $data['body'];
/*
* 2) Submit CURL request to local elasticsearch (http://localhost:9210/api/fud_fret_web/)
*/
$url = ELASTIC_BASE_URL . $elasticSubPath;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $elasticBody);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
/*
* 3) Return (and transform?) results
*/
header('Content-Type: application/json');
echo $response;
exit;
Search.comopnent.ts
this.http.Search(query).then(
(response: any) => { ....
感谢您的帮助。
答案 0 :(得分:2)
只返回一个可观察对象并订阅它会更简单。除非我误解了您的目标?
http.service.ts
Search(body: any): Observable<any> {
const proxyBody = {
path: 'doctyp136,doctyp135,doctyp134/_search',
body: body
};
return this.http.post( environment.elastic_url, proxyBody, {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})})
}
Search.comopnent.ts
this.http.Search(query).subscribe(
data => {
console.log(data);
}
)
或者,如果您真的希望将其作为一个承诺,则可以使用以下内容将其转换为一个。
http.service.ts
Search(body: any): Promise<any> {
const proxyBody = {
path: 'doctyp136,doctyp135,doctyp134/_search',
body: body
};
return this.http.post( environment.elastic_url, proxyBody, {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})}).toPromise()
}
Search.comopnent.ts
this.http.Search(query).then(
data => {
console.log(data);
}
)