从Angular 2中的服务到组件获取异步数据

时间:2017-06-02 18:15:09

标签: angular asynchronous service components

我有一个Workplaces服务,它从json文件中获取asynron数据:

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请求时,当我的组件被初始化时,数据不会加载到我的服务中。如何从我的服务中获取数据? 我不想在我的Component中使用subscribe()。它应该提供我的服务。

感谢。

1 个答案:

答案 0 :(得分:0)

尝试将服务中的所有工作场所公开并访问它。当你执行getAllWorkplaces()方法时,它会给出一个对象的快照,在这一点上,同步调用可能没有结束。