【发布时间】:2017-11-04 05:32:56
【问题描述】:
我有一个工作场所服务,它从 json 文件中获取异步数据:
export class WorkplaceService{
private allWorkplaces:Workplace[] = new Array();
constructor(private http: Http){
this.readWorkplaceDataFromFile().subscribe(data => this.allWorkplaces=data, error => console.log(error));
}
private readWorkplaceDataFromFile(): Observable<Workplace[]> {
return this.http.get('assets/workplaces.json').map((response: Response) => {
return <Workplace[] > response.json()
}).catch(this.handleError);
}
public getAllWorkplaces():Workplace[] {
return this.allWorkplaces;
}
}
现在我需要将这些数据放入我的 WorkplacesComponent。我正在尝试这个:
export class WorkplaceManagementComponent implements OnInit{
allWorkplaces: Workplace[] = new Array();
constructor(private storage: ProductionProgramStorage, private workplaces: WorkplaceService) {
}
ngOnInit() {
this.allWorkplaces = this.workplaces.getAllWorkplaces();
}
但是当我执行异步 http 请求时,当我的组件被初始化时,数据不会加载到我的服务中。如何从我的服务中获取数据? 我不想在我的组件中使用 subscribe()。 它应该为我服务。
谢谢。
【问题讨论】:
-
getAllWorkplaces 函数在您的服务中的哪个位置?
-
我编辑了我的问题。忘记放了。
标签: angular asynchronous service components