【问题标题】:Get asynchron data from Service to Component in Angular 2在Angular 2中从服务到组件获取异步数据
【发布时间】: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


【解决方案1】:

尝试将服务中的 allWorkplaces 公开并访问它。当您执行 getAllWorkplaces() 方法时,它会提供对象的快照,此时异步调用可能尚未结束。

【讨论】:

  • 我已经试过了,这个也不管用。异步调用仍未结束..
猜你喜欢
  • 2016-01-21
  • 1970-01-01
  • 2017-10-19
  • 2019-05-26
  • 1970-01-01
  • 1970-01-01
  • 2020-09-08
  • 1970-01-01
  • 2023-04-02
相关资源
最近更新 更多