代码之家  ›  专栏  ›  技术社区  ›  Sohail

订阅后返回json格式的数据

  •  0
  • Sohail  · 技术社区  · 8 年前

    我正在使用Angular 5,希望在订阅服务后以json格式从函数GetDionareaResults返回数据

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

    调用此函数后, this.totalAttacks 打印未定义。

    getTotalAttack() {
           this.totalAttacks = this.getDionaeaResults("some query")
           console.log(this.totalAttacks,'attacks')
    }
    
    2 回复  |  直到 8 年前
        1
  •  1
  •   Nolan Walker    8 年前

    建议使用Obserable。map()函数。

    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); }
      );
    }
    
        2
  •  1
  •   AJF    8 年前

    this.getDionaeaResults 正在返回 undefined 因为您调用的服务是异步的,所以您必须等待subscribe回调。因为可观察的是异步调用

    this.data=res 
    

    可能在return语句之后执行。也许你可以这么说 dionaeaService 直接在内部 getTotalAttack() 函数,如下所示:

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