Angular 2 服务未更新到组件

Angular 2 Service not updating to component

我正在调用服务以从 MongoDB 获取数据。 这部分似乎在工作,并且在控制台中正确记录。

这个响应非常大,可能需要大约 8 秒的时间才能让数据完全进入。为此,我希望能够在检索到数据后更新组件中的 data[]

我当前的解决方案不起作用,我想知道实时检索它的正确和最佳实践。即使响应需要更长的时间。

getData 服务调用

export class DataService {
dataArray: any[];
constructor(private http: Http){}

//get all data
getData(): any {
    console.log('Api is calling getData...');
    this.http.get('http://localhost:8080/api/data').map((res: Response) => res.json()).subscribe((res: any) => {
        this.dataArray = res;
   console.log('JSON: ' + this.dataArray);
   return this.dataArray;
 });
}
}

已正确导入 MainComponent,没有错误。

主要组件

export class MainComponent implements OnInit{
data: Array<any>;
//Inject service here to use for getting data
constructor(private dataService: DataService){}

ngOnInit(){
    //Set View Data with Request from Server
    this.data = this.dataService.getData();
    console.log("Data: " + this.data);
}
}

如您所料,我在 MainComponent 中的日志没有显示适当的数据,实际上显示的是 undefined。这恰好是一个我似乎无法克服的错误。我知道必须有一个简单的解决方案,但出于某种原因,我找不到直接的答案。

这就是我希望得到的,是关于当服务从请求

收到数据时如何更新 MainComponent 数组的答案

我认为你应该 return Observable 在你的服务和你的 MainComponent 订阅它(在订阅里面做数据的初始化)

来自 angular 文档的示例:

英雄服务:

getHeroes(): Observable<Hero[]> {
return this.http.get(this.heroesUrl)
              .map(this.extractData)
              .catch(this.handleError);
}

部分组件

this.heroService.getHeroes()
               .subscribe(
                 heroes => this.heroes = heroes,
                 error =>  this.errorMessage = <any>error);

Check documentation

如果您不想订阅,只是抛出另一个选项。

作为旁注,即使以下内容有效,它也会打印响应,但不会打印响应,因为这是异步的,并且 console.log 在数据完全接收之前执行。但如果有效,

this.data = this.dataService.getData();
console.log("Data: " + this.data);

data 将是一个 Observable,您仍然需要订阅它。它可以像 kriss 建议的那样完成,或者你可以像这样离开它:this.data = this.dataService.getData(); 然后使用 async 管道,它会为你做订阅。因此,如果数据是一个数组,那么您将在模板中执行以下操作:

<div *ngFor="let d of data | async">
  {{d.myProperty}}
</div>

只是抛出这个选项:)