Javascript 在angular 4中呈现函数后,将数据从服务共享到组件
我有一个服务,在服务中,我有一个“cohortabsresult”方法,它设置了charts数组。我想在“chart.component”中使用此arryJavascript 在angular 4中呈现函数后,将数据从服务共享到组件,javascript,angular,Javascript,Angular,我有一个服务,在服务中,我有一个“cohortabsresult”方法,它设置了charts数组。我想在“chart.component”中使用此arry 将CohortService导入组件,将其添加到@component中的提供程序中,现在您可以访问服务中的变量:D import { CohortService } from '../../cohort.services'; // whatever the path is.. @Component({ selector: '', t
将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)
}
}
在什么时候运行
coorttabsresult
函数来填充图表
数组?这不在代码中。它将不起作用,因为将其放入组件的提供程序数组将生成服务的新实例,因此不会设置charts值。他可以在组件构造函数中注入服务。@geoautome:您可以在app.module.ts中注入服务。是的,在他的示例中,情况显然是这样的,因为他已经在另一个组件构造函数中使用了服务。因此,在组件中重新提供它将不起作用,并导致创建一个新实例。所以他只需要在他的组件中使用它。
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)
}
}
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)
}
}