In this tutorial, we’re gonna look at how to add ElasticSearch to an Angular 6 Project.
Related Posts:
– Angular 6 ElasticSearch example – Add Document to Index
– Angular 6 ElasticSearch example – Get All Documents in Index
– Angular 6 ElasticSearch example – Documents Pagination with Scroll
– Angular 6 ElasticSearch example – simple Full Text Search
** Elasticsearch Tutorials **
Contents
Install ElasticSearch
Go to ElasticSearch guide – Getting Started » Installation and follow step by step to install ElasticSearch.
Test local install of ElasticSearch
– by command line:
curl -XGET localhost:9200
– or enter http://localhost:9200/
url on your Browser.
The result should be like this:
{ "name":"first_node_test", "cluster_name":"elasticsearch", "cluster_uuid":"E8eoz-uWT0Gxi-ygUIB10Q", "version":{ "number":"6.3.2", "build_flavor":"unknown", "build_type":"unknown", "build_hash":"053779d", "build_date":"2018-07-20T05:20:23.451332Z", "build_snapshot":false, "lucene_version":"7.3.1", "minimum_wire_compatibility_version":"5.6.0", "minimum_index_compatibility_version":"5.0.0" }, "tagline":"You Know, for Search" } |
Add ElasticSearch to Angular 6 Project
1. Install the type definition
Run command:
npm install --save-dev @types/elasticsearch
You will see an elasticsearch directory in node_modules folder:
2. Add dependency
Open package.json in your Angular 6 Project, add:
... "dependencies": { "elasticsearch-browser": "^15.1.1", ... }, ... |
Re-install your Angular 6 Project:
npm install
Use ElasticSearch in Angular 6 Project
1. Import and use
import * as elasticsearch from 'elasticsearch-browser'; //... private client: elasticsearch.Client private connect() { this.client = new elasticsearch.Client({ host: 'localhost:9200', log: 'trace' }); } |
or:
import { Client } from 'elasticsearch-browser'; //... private client: Client; private connect() { this.client = new Client({ host: 'http://localhost:9200', log: 'trace' }); } |
2. Add CORS config
To work with ElasticSearch, we need to enable CORS by adding in /config/elasticsearch.yml:
http.cors.enabled : true http.cors.allow-origin : "*" http.cors.allow-methods : OPTIONS, HEAD, GET, POST, PUT, DELETE http.cors.allow-headers : X-Requested-With,X-Auth-Token,Content-Type, Content-Length |
3. Ping to test
Write the code below to ping to ElasticSearch:
this.client.ping({ requestTimeout: Infinity, body: 'hello JavaSampleApproach!' }); |
Open Browser to check, it should be:
TRACE: 2018-08-13T07:34:46Z -> HEAD http://localhost:9200/ hello grokonez! <- 200 |
Practice
1. Generate Service & Component
Run cmd:
– ng g s elasticsearch
– ng g c test-es
=> Project Structure:
=> App Module:
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { TestEsComponent } from './test-es/test-es.component'; @NgModule({ declarations: [ AppComponent, TestEsComponent ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } |
2. ElasticSearch Service
elasticsearch.service.ts
import { Injectable } from '@angular/core'; import { Client } from 'elasticsearch-browser'; import * as elasticsearch from 'elasticsearch-browser'; @Injectable({ providedIn: 'root' }) export class ElasticsearchService { private client: Client; constructor() { if (!this.client) { this._connect(); } } private connect() { this.client = new Client({ host: 'http://localhost:9200', log: 'trace' }); } private _connect() { this.client = new elasticsearch.Client({ host: 'localhost:9200', log: 'trace' }); } isAvailable(): any { return this.client.ping({ requestTimeout: Infinity, body: 'hello grokonez!' }); } } |
2. Test Component
test-es.component.ts
import { Component, OnInit, ChangeDetectorRef } from '@angular/core'; import { ElasticsearchService } from '../elasticsearch.service'; @Component({ selector: 'app-test-es', templateUrl: './test-es.component.html', styleUrls: ['./test-es.component.css'] }) export class TestEsComponent implements OnInit { isConnected = false; status: string; constructor(private es: ElasticsearchService, private cd: ChangeDetectorRef) { this.isConnected = false; } ngOnInit() { this.es.isAvailable().then(() => { this.status = 'OK'; this.isConnected = true; }, error => { this.status = 'ERROR'; this.isConnected = false; console.error('Server is down', error); }).then(() => { this.cd.detectChanges(); }); } } |
test-es.component.html
<h3 class="col-md-12 text-center">Elasticsearch server status: {{status}}</h3> |
4. App Component
app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'grokonez'; description = 'Angular - Elasticsearch'; } |
app.component.html
<div class="container" style="width: 400px"> <div style="color: blue; margin-bottom: 20px"> <h1>{{title}}</h1> <h3>{{description}}</h3> </div> <app-test-es></app-test-es> </div> |
5. Check Result
Run Angular 6 App, go to http://localhost:4200/
:
Open Browser Console, we can see:
Hello sir, when i try to execute angular6elasticsearch application, i am getting below error. But here elasticsearch running.
Error:-
—-
grokonez
Angular – Elasticsearch
Elasticsearch server status: ERROR
console erro:-
—-
elasticsearch.js:31361 ERROR: 2018-11-02T06:18:29Z
Error: Request error, retrying
HEAD http://localhost:9200/ => Request failed to complete.
at Log.error (http://localhost:4200/vendor.js:71724:56)
at checkRespForFailure (http://localhost:4200/vendor.js:78332:18)
at XMLHttpRequest.xhr.onreadystatechange [as __zone_symbol__ON_PROPERTYreadystatechange] (http://localhost:4200/vendor.js:84621:7)
at XMLHttpRequest.wrapFn (http://localhost:4200/polyfills.js:3510:39)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:2743:31)
at Object.onInvokeTask (http://localhost:4200/vendor.js:34899:33)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:2742:36)
at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (http://localhost:4200/polyfills.js:2510:47)
at ZoneTask.push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (http://localhost:4200/polyfills.js:2818:34)
at invokeTask (http://localhost:4200/polyfills.js:3862:14)
localhost/:1 Access to XMLHttpRequest at ‘http://localhost:9200/’ from origin ‘http://localhost:4200’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
elasticsearch.js:31361 TRACE: 2018-11-02T06:18:29Z
-> HEAD http://localhost:9200/
<- 0
Hi, have you done this step:
Add_CORS_config
I’ve the same issue, and done that step.
@arda can you find the solution?
Had this issue and i have figured out that there is another elasticsearch.yml
Try the one under C:\ProgramData\Elastic\Elasticsearch\config
Edit it and add the CORS cofiguration (responsibly) as the “*” is quite dangerous
Hope this will help you
Hello Sir, how to add headers and basic authorization (header)?
I noticed in Angular7 it required me to specify that isAvailable() to include that it returns a Promise, otherwise I get a complaint that
isAvailable
is not a function.It stripped out my <any> after the Promise type.
Access to XMLHttpRequest at ‘http://localhost:9200/index/****/***’ from origin ‘http://localhost:4200’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
i also getting the above error, can anyone tell how to solve this issue??
information: Added below cors commands in my config/elasticsearch.yml:
http.cors.enabled : true
http.cors.allow-origin : “*”
http.cors.allow-methods : OPTIONS, HEAD, GET, POST, PUT, DELETE
http.cors.allow-headers : X-Requested-With,X-Auth-Token,Content-Type, Content-Length
Even i face the same issue