How can i store a JSON object or its particular values for further use (Angular)? The only thing i can do is just log them

Viewed 70

I'm using elasticsearch in order to create some visualization with kibana based on data i'm gathering from a sensor board, however I need some of this data in my Angular 9 application. I'm using elastic api's to get data and the only thing i can do is just log them, but i can't store them for further use. I tried the same thing with python and it worked well. What am i doing wrong with Angular?

"THIS IS THE CODE"

es.getSource({id: "1", index:"acc_sensor", _source:"true"},
function(error,response){
  if(error){
   console.log("search error: "+error);
  }
  else{
   console.log("---Response---");
   console.log(response);
   console.log("---particular value---")
   this.roll = response['roll'];
   console.log(this.roll);
  }});

"AND THIS IS WHAT I HAVE IN THE CONSOLE AFTER RUNNING THE CODE"

This is what i have in the console after running the code

1 Answers

You can wrap your elastic search call in a promise in a corresponding service class and bind to the result in your view component. Something like this (still needs error-handling):

export interface ElasticSearchParam {
    id: string;
    index: string;
    _source: string;
}

// Service
 @ Injectable()
export class ElasticSarchService {

    search(searchObj: ElasticSearchParam) {
        return new Promise( (resolve, reject) => {
            es.getSource(searchObj, (error, response) => {
                if (error) {
                    reject(error);
                } else {
                    resolve(response);
                }
            });
        });

    }
}

// your view component
@Component({
selector: "app",
template: `...<p>The roll is: {{roll}}</p>...` 
})
class YourComponent {

    private roll: any; // the actual data you want to use from the elasticSearch result

    constructor(private elasticSearchService: ElasticSarchService) {}

    async doSearch(term: string) {
        const elasticSearchResult = await this.elasticSearchService.search({
                id: "1",
                index: "acc_sensor",
                _source: "true"
            });
        this.roll = elasticSearchResult.roll; // or whatver you'd like to do with the response
    }
}
Related