Sohail
Sohail

Reputation: 597

Return data in json after subscribe

I am using Angular 5 and want to return data from function getDionaeaResults in json format after subscribing to service

getDionaeaResults(sql) : any {
        this.dionaeaService.getDionaeaConnectionLogs(sql).subscribe(res => {
         this.data = res;
        }),
        (error: any) => {
                console.log(error);
        });
        return this.data;
    }

After calling this function, this.totalAttacks prints undefined.

getTotalAttack() {
       this.totalAttacks = this.getDionaeaResults("some query")
       console.log(this.totalAttacks,'attacks')
}

Upvotes: 0

Views: 228

Answers (2)

Nolan Walker
Nolan Walker

Reputation: 352

Would suggest using the Obseravable .map() function.

getDionaeaResults(sql) : Observable<any> {
  return this.dionaeaService
             .getDionaeaConnectionLogs(sql)
             .map(res => res);
}

getTotalAttack(sql){
  this.getDionaeaResults("some query")
      .subscribe(
          res => { this.totalAttacks = res; },
          err => { console.log(err); }
  );
}

Upvotes: 1

Saqib Hussain
Saqib Hussain

Reputation: 135

this.getDionaeaResults is returning undefined because the service you're calling is asynchronous you have to wait for the subscribe callback. as Observables are asynchronous calls

this.data=res 

might execute after the return statement. You can perhaps call that dionaeaService directly inside getTotalAttack() function, like this:

getTotalAttack(sql){
   this.dionaeaService.getDionaeaConnectionLogs(sql).subscribe(res => {
      this.totalAttacks = res;
    }),
    (error: any) => {
            console.log(error);
    });
 }

Upvotes: 1

Related Questions