2017-01-24 76 views
0

我是Angular 2中的新用户。我在本地机器中托管了一项服务。该服务工作正常。但是当我要从Angular 2的服务中检索数据时,如下所示:数据成功检索并登录到我的控制台中。但是当我在我看来要显示价值的时候。 “this.myPurchaseItems”是空的。这是为什么?请帮忙。谢谢Angular 2中的服务不会向html组件返回值

calling file...... 
this._service.getMyPracticeTest(this.uid).subscribe(data => { this.myPurchaseItems = data }); 
------------------------------------------------------ 

service.ts file..... 
getMyPracticeTest(uid: string){ 
    return this._http.get('http://localhost:49753/RestServiceImpl.svc/getMyPracticeTest/' + uid) 
     .map(res => res.json()) 
     .do(data => console.log("GetMyPracticeTest" + JSON.stringify(data))) 
     .catch(this.handleError); 
} 
------------------------------------------------------ 

<table class="table"> 
     <tr><th>ID</th></tr> 
     <tr *ngFor="let data of myPurchaseItems"> 
      <td>{{data.Purchase_ID}}</td> 
     </tr> 
</table> 

解决问题的办法。

getMyPracticeTest(uid: string){ 
    return this._http.get('http://localhost:49753/RestServiceImpl.svc/getMyPracticeTest/' + uid) 
    .map(data => { 
     data.json(); 
     // the console.log(...) line prevents your code from working 
     // either remove it or add the line below (return ...) 
     console.log("I CAN SEE DATA HERE: ", data.json()); 
     return data.json(); 
} 
+0

假设第三个文件是第一个文件的视图,您只是名称与“myPurchaseItems”和“myTestData” – matmo

+0

错字错误不匹配。这是myPurchaseItems。 – wal

+0

如果你的数据是一个数组,那么它理论上应该工作得很好。你有没有把ChangeDetectionStrategy改成OnPush?如果没有,一切都应该按照你的例子工作。很难评论任何进一步没有plunkr。 – matmo

回答

0

你没有太多在这里去,但我最近遇到了麻烦与我*ngFor绑定调用它,那你的方式。相反,试试这个

<tr *ngFor="let Purchase_ID of myPurchaseItems.data"> 
    <td>{{Purchase_ID}}</td> 
</tr> 

认为这样做是对我来说,如果不工作,张贴代码到您的组件和服务,所以我们可以在你在做什么更好看。

0

我以前有类似的问题,这个问题是更改检测没有运行。

你可以试试这个,你的组件构造

constructor(private cdRef:ChangeDetectorRef) { } 

里面里面你完成块

this._service.getMyPracticeTest(this.uid).subscribe(data => 
{ 
    this.myPurchaseItems = data; 
    this.cdRef.detectChanges(); 
}); 

ChangeDetectorRef@angular/core

进口,您可以阅读更多有关ChangeDetectorRefHere

+0

为什么要这样做,而不是找到一个理由? –

+0

我正在离开体验,我花了很多天的时间试图找到问题,以便为什么我的用户界面不会在更新Firebase数据库之后更新,甚至在没有问题的情况下提出问题。这最终使用'ChangeDetectorRef'或'NgZone'。 OP可以随时尝试我提出的建议,如果有效,那么我们可以深入一点,在尝试我猜测时没有任何伤害。 –