在角度4中渲染函数后,将数据从服务共享到组件

时间:2018-06-18 12:23:22

标签: javascript angular

我有服务,在服务中,我有一个“cohortTabsResult”方法whitch设置图表数组。我想在“chart.component”中使用这个arry

export class CohortService {
 public charts: Array<any>;

 cohortTabsResult(obj){
    this.charts = []
    const subscription = this.cohortDataReq(obj).subscribe(res => {
        if(res.status !== 500){

            const dataObj = {
                definedChart: obj.graph_type,
                definedChartData: []     
            };
            this.charts.push(dataObj);
            const response = res.json() 
            //console.log(response)

            if (response.error) {
                //this.isLoaded = false;                              
            } 
            else{
                 Array.prototype.forEach.call(response.data, dataRes => {
                    const newData = this.getChartDataFormat(dataRes, obj.graph_type, "userType")
                    dataObj.definedChartData = _.cloneDeep(newData);
                  });

            } 

        }

    });

}

}

这是我的chart.component,我得到的是空数组。

export class ChartCohortComponent implements OnInit{
  charts: any;
  constructor(private cohortService: CohortService, private route: 
  Router, public activatedRoute: ActivatedRoute) {
       this.charts = this.cohortService.charts;
  }


  ngOnInit(){ 

    console.log("ch", this.charts)

  }
 }

1 个答案:

答案 0 :(得分:0)

将CohortService导入您的组件,将其添加到@component中的提供程序,现在您可以访问服务中的变量。 :d

import { CohortService } from '../../cohort.services'; // whatever the path is.. 
@Component({
  selector: '',
  templateUrl: '',
  styleUrls: [''],
  providers: [CohortService]
})
export class ChartCohortComponent implements OnInit{
  charts: any;
  constructor(private cohortService: CohortService, private route: 
  Router, public activatedRoute: ActivatedRoute) {
       this.charts = this.cohortService.charts;
  }


  ngOnInit(){ 

    console.log("ch", this.charts)

  }
 }