Angular 2从订阅返回数据

时间:2017-07-20 09:15:53

标签: angular observable

这是我的服务

 countGroupByEtat(): Observable<number[]> {
    return this.http.get(this.url + 'GroupByEtat', { headers: this.prepareHeaders() })
        .map((res: Response) => {
            let object: Array<any> = [];
            let jsonResults: Array<any> = res.json();
            jsonResults.forEach((jsonResult) => {
                object.push(jsonResult);
            });
            return object;
        })
}

和我的方法

  getGroupByEtat(): number[] {
    this.serviceDossier.countGroupByEtat()
      .subscribe((data: number[]) => {
        this.objects = data;
        console.log("subsc"+ this.objects)

      })
    return this.objects;
  }

当我想在this.objects结束后获得subscribe的值时,我收到一个空的数组,帮助!

1 个答案:

答案 0 :(得分:2)

将其更改为:

 getGroupByEtat(): number[] {
    return this.serviceDossier.countGroupByEtat()
      .subscribe((data: number[]) => {
        this.objects = data;
        console.log("subsc"+ this.objects)

        return this.objects;
      })

  }