Search code examples
servicepromisereturnangular5observers

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')
}

Solution

  • 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); }
      );
    }